Skip to content

Commit

Permalink
feat: implement when
Browse files Browse the repository at this point in the history
  • Loading branch information
customcommander committed Jul 16, 2021
1 parent 1ae7d5f commit c3a135e
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -349,5 +349,31 @@ module.exports = {
if (fn.length === 0) throw new Error(`juxt: called with no arguments`);
fn.forEach((f, i) => assert_function(f, `juxt: arg at ${i} is not a function`));
return (...args) => fn.map(f => f(...args));
}
},

/**
* Returns `g(x)` if `f(x)` returns `true`.
* Returns `undefined` otherwise.
*
* @example
* ```javascript
* when(eq(40), add(2))(40);
* //=> 42
*
* when(eq(40), add(2))(41);
* //=> undefined
* ```
*
* @public
* @param {function(?): boolean} f Predicate. Must return `true` not thruthy.
* @param {function(?): ?} g Function applied to `x` if predicate is satisfied.
* @param {?} x
* @returns {?}
* @throws When either `f` or `g` is not a function
*/
when: _curry((f, g, x) => {
assert_function(f, 'when: `f` is not a function');
assert_function(g, 'when: `g` is not a function');
if (f(x) === true) return g(x);
})
};
31 changes: 31 additions & 0 deletions test/when.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const td = require('testdouble');
const test = require('tape');
const {when: sut} = require('..');

test('when throws an error when either `f` or `g` is not a function', t => {
t.throws(() => sut(td.func())(42)('x'));
t.throws(() => sut(42)(td.func())('x'));
t.end();
});

test('when returns `g(x)` if `f(x)` returns `true`', t => {
const f = td.func();
const g = td.func();

td.when(f(1)).thenReturn(true);
td.when(f(2)).thenReturn(false);
td.when(f(3)).thenReturn('truthy');

td.when(g(1)).thenReturn('OK');

t.same(sut(f)(g)(1), 'OK',
'expected `g(x)` because f(x) returned `true`.');

t.same(sut(f)(g)(2), undefined,
'expected `undefined` because `f(x)` returned `false`.');

t.same(sut(f)(g)(3), undefined,
'expected `undefined` because `f(x)` returned truthy not `true`.');

t.end();
});

0 comments on commit c3a135e

Please sign in to comment.