Skip to content

Commit

Permalink
feat: implement flip
Browse files Browse the repository at this point in the history
  • Loading branch information
customcommander committed Feb 27, 2021
1 parent b3e872c commit b6409df
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,33 @@ module.exports = {
curry: fn => {
assert_function(fn, 'curry: `fn` is not a function');
return _curry(fn);
},

/**
* Takes a function `fn` of arity 2 (or more) and returns
* a (curried) version of it in which the first two parameters
* have been swapped.
*
* @example
* ```javascript
* const x = (a, b, c) => a + b + c;
* x('foo', 'bar', 'baz');
* //=> 'foobarbaz'
*
* const y = flip(x);
* y('foo')('bar', 'baz');
* //=> 'barfoobaz'
* ```
*
* @public
* @param {function()} fn
* @return {function()}
*/
flip: fn => {
assert_function(fn, 'flip: `fn` is not a function');
return _curry(function (a, b) {
const [x, y, ...z] = Array.from(arguments);
return fn(y, x, ...z);
});
}
};
};
28 changes: 28 additions & 0 deletions test/flip.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const test = require('tape');
const td = require('testdouble');
const {flip} = require('../dist');

test('flip inverts the order of the first two parameters.', t => {
const fn = td.function();
const flipped = flip(fn);
flipped('foo')('bar');
td.verify(fn('bar', 'foo'));
flipped('baz', 'bat');
td.verify(fn('bat', 'baz'));
t.end();
});

test('flip forwards the rest of the parameters.', t => {
const fn = td.function();
const flipped = flip(fn);
flipped('foo')('bar', 'baz');
td.verify(fn('bar', 'foo', 'baz'));
flipped('foo', 'bar', 'baz', 'bat');
td.verify(fn('bar', 'foo', 'baz', 'bat'));
t.end();
});

test('flip fails when not given a function.', t => {
t.throws(() => flip([]));
t.end();
});

0 comments on commit b6409df

Please sign in to comment.