1

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.

Malvinka
  • 1,185
  • 1
  • 15
  • 36

4 Answers4

1

Do it in one line with ternary operator :

value = val == "true" ? true : (val == "false" ? false : val);

Johan
  • 2,088
  • 2
  • 9
  • 37
  • 2
    You sure can, but is it really more clear that OP's initial version? Easier to maintain and read? I'd prefer OP's version. – Ivar Jan 09 '23 at 11:30
  • He asked for a one line. This is one. And very easy to read and understand – Johan Jan 09 '23 at 13:34
0

let val = 'false';

val = {'true': true, 'false': false, [val]:val}[val]

console.log(val)
Andrew Parks
  • 6,358
  • 2
  • 12
  • 27
0

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'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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 });
});
Thomas
  • 11,958
  • 1
  • 14
  • 23