Last active
December 7, 2015 09:46
-
-
Save roobie/589f1d4e5ee11654a92e to your computer and use it in GitHub Desktop.
cond, almost like in lisp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| @example: | |
| ```javascript | |
| const result = cond( | |
| [false, () => 'this should not be'], | |
| [Boolean(), () => 'Boolean defaults to false'], | |
| [true, () => '`true` can be considered the "catch all" symbol in a cond expr.'] | |
| ); | |
| ``` | |
| ```javascript | |
| const fibonacci = function fib(n) { | |
| return cond( | |
| [n === 0, () => 0], | |
| [n === 1, () => 1], | |
| [true, () => fib(n - 1) + fib(n - 2)] | |
| ); | |
| }; | |
| const result = fibonacci(7); // -> 13 | |
| ``` | |
| */ | |
| export default function cond(...conditions) { | |
| // loop over each of the conditions. | |
| for (let [test, fn] of conditions) { | |
| if (test) { | |
| return fn(); | |
| } | |
| } | |
| // let off a warning, because falling through | |
| // in a cond should be considered undefined behaviour. | |
| console.warn(new Error('no conds matched')); | |
| return void 0; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment