DEV Community

Jan Küster
Jan Küster

Posted on

JavaScript code puzzle: convert a Boolean to Number

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.

Top comments (2)

Collapse
 
snigo profile image
Igor Snitkin

Up to 3 characters:

const fn_not = b => ~~b;
const fn_inc = b => b++;
const fn_nry = b => +b; // might fall under `toNumber` implementation
Enter fullscreen mode Exit fullscreen mode

Cool stuff, keep it up!

Collapse
 
jankapunkt profile image
Jan Küster

Another solution with same length would be

Spoiler
fn=b=>b/1
Enter fullscreen mode Exit fullscreen mode

I counted the function too, which I came up to 9 characters