If you have no shame:
String.prototype.toTruth = function () {
const value = this.valueOf();
return value === 'true' ? true : value === 'false' ? false : undefined;
};
'true'.toTruth() // true
'false'.toTruth() // false
'falsest'.toTruth() // undefined
''.toTruth() // undefined
(Disclaimer: For the love of ECMA, don't do this.)
It's an interesting question, though, with more repercussions than one might expect.
I called it toTruth and not toBoolean because its return value can't always be a Boolean. One could argue that '' should return false, but what about other strings? Is it true or false?
Unless you use strict typing everywhere, with a 'true' | 'false' union, there's no guarantee that your string is going to contain either true or false (or nothing). So logically, you have to allow for a third value, undefined. (Or throw an error? No thanks.)
This means it actually becomes ternary logic, where undefined is similar to SQL's NULL (neither true nor false). That makes it much more complicated than a simple true/false predicate. Especially when you add JavaScript's truthiness to the equation, where an undefined value might be evaluated as false (falsy).
If you have no shame and actually want to use this (dear god), you should explicitly check against the value you want with === and not use negation (unless you know what you're doing, keep in mind that it's ternary logic):
const input = 'foo'; // or anything else but 'true' or 'false'
input.toTruth() // undefined
!input.toTruth() // true (misleading, it's not false)
input.toTruth() !== true // true (misleading, it's not false)
input.toTruth() === false // false (correct)
input.toTruth() === true // false (correct)
input.toTruth() === undefined // true (correct)
I like JavaScript and I like ternary logic. But carelessly combining the two is a recipe for disaster.
A statically typed language like TypeScript does make it a lot easier. However, the same caveats apply when your code is exposed to code or input you don't control.
type BooleanString = 'true' | 'false'
function toBoolean(predicate: BooleanString): boolean {
return predicate === 'true';
}
function toTruth(predicate: string): boolean | undefined {
return predicate === 'true' ? true : predicate === 'false' ? false : undefined;
}
string=(string==String(string?true:false))?(string?true:false):(!string?true:false);function parseBool(val) { return val === true || val === "true" }function checkBool(x) { if(x) {return true;} else {return false;} }if (checkBool(x) != false) { ... } else { ... }!!(parseInt(value) || value === "true")