What is the most efficient one-liner (if possible) for:
if (val == "true"){
value = true;
}
else if (val == "false"){
value = false;
}
else {
value = val;
}
val is string.
What is the most efficient one-liner (if possible) for:
if (val == "true"){
value = true;
}
else if (val == "false"){
value = false;
}
else {
value = val;
}
val is string.
Do it in one line with ternary operator :
value = val == "true" ? true : (val == "false" ? false : val);
let val = 'false';
val = {'true': true, 'false': false, [val]:val}[val]
console.log(val)
You could take an object with null colalescing with the given string.
const
bOrS = v => ({ true: true, false: false }[v] ?? v);
console.log(bOrS('true'), typeof bOrS('true'));
console.log(bOrS('false'), typeof bOrS('false'));
console.log(bOrS('foo'), typeof bOrS('foo'));
You can do it with just a &&
and a ||
:
value = val == "true" || val != "false" && val;
but will you still understand it when you read it in a month or two?
const toBool = val => val == "true" || val != "false" && val;
["true", "false", "something", ""].forEach(val => {
const value = toBool(val);
console.log({ val, value, type: typeof value });
});