Skip to content

Commit

Permalink
feat: implement on
Browse files Browse the repository at this point in the history
  • Loading branch information
customcommander committed Jul 15, 2021
1 parent 979fa6b commit 482af83
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,5 +212,32 @@ module.exports = {
if (fn[i](...args) === true) return fn[i+1](...args);
}
};
}
},

/**
* Takes a binary function `f` and a unary function `g` and returns
* a curried binary function that takes an `a` and a `b`.
* Applies `f` to the result of `g(a)` and `g(b)`.
*
* @example
* > Building a case-insensitive string comparison function.
*
* ```javascript
* const streqi = on(eq, lower); // i.e. (a, b) => eq(lower(a), lower(b))
*
* streqi('FOObar', 'fooBAR');
* //=> true
* ```
*
* @public
* @param {function(?, ?): ?} f
* @param {function(?): ?} g
* @return {function(?, ?): ?}
* @throws When either `f` or `g` is not a function.
*/
on: _curry((f, g) => {
assert_function(f, 'on: `f` is not a function');
assert_function(g, 'on: `g` is not a function');
return _curry((a, b) => f(g(a), g(b)));
})
};
21 changes: 21 additions & 0 deletions test/on.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const td = require('testdouble');
const test = require('tape');
const {on: sut} = require('../');

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

test('on returns a binary function and applies `f` to `g(a)` and `g(b)`', t => {
const f = td.func();
td.when(f(40, 2)).thenReturn(42);

const g = td.func();
td.when(g(39)).thenReturn(40);
td.when(g(1)).thenReturn(2);

t.same(sut(f)(g)(39)(1), 42);
t.end();
});

0 comments on commit 482af83

Please sign in to comment.