JavaScript code puzzle: convert a Boolean to Number

Jan Küster - Feb 19 '22 - - Dev Community

Write a function fn that receives a Boolean and returns it's representation as a Number. So true becomes 1 and false becomes 0.

Contstraints:

  • no Number constructor or any of it's prototype allowed
  • no Math functions allowed
  • no toNumber implementations allowed either
  • Strings of numbers, such as '1' and '0' do not count
  • Assume the function always receives a valid boolean (so no null or undefined or other types need to be considered).

Tests:

 console.assert(fn(true) === 1)
 console.assert(fn(false) === 0)
Enter fullscreen mode Exit fullscreen mode

Note:

It's marked as #beginners, because it's solution easier than you might think.

Bonus:

It's possible to solve it with 9 characters overall.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player