Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Bite-size coding challenge: implement if/else in JavaScript without `if` or `?:`
4 points by markchristian on Jan 10, 2020 | hide | past | favorite | 2 comments
Here's a bit of Friday fun for you: your mission, should you choose to accept it, is to implement if/then logic in JavaScript without using `if` or the ternary operator `?:`.

Implement a function with the following signature:

```` function ifThenElse(cond, trueFn, falseFn) { } ````

If `cond` is truthy, execute `trueFn`, otherwise execute `falseFn`. `ifThenElse` should not have a return value.

Here's a gist that contains a very tiny test harness: https://gist.github.com/shinypb/befb5363395c754758b157b850cf747a

Put your implementations into your own gist and then reply to this thread.

I'm curious to see what sort of horrible atrocities you can all come up with. :) Happy hacking!

PS: Here are my two ideas:

https://gist.github.com/shinypb/85d6dd19e712f4d7962bd4c0cb30dfec

https://gist.github.com/shinypb/78dd126d946bec6cc77245d40d0748cb



  function ifThenElse(cond, trueFn, falseFn) {
      ({ true: () => trueFn(), false: () => falseFn() })[cond]();
  }


  function ifThenElse(cond, trueFn, falseFn) {
    cond && trueFn();
    cond || falseFn();
  }




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: