Skip to content

Instantly share code, notes, and snippets.

@roobie
Last active December 7, 2015 09:46
Show Gist options
  • Select an option

  • Save roobie/589f1d4e5ee11654a92e to your computer and use it in GitHub Desktop.

Select an option

Save roobie/589f1d4e5ee11654a92e to your computer and use it in GitHub Desktop.
cond, almost like in lisp
/**
@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