Skip to content

Instantly share code, notes, and snippets.

@rohanorton
Last active February 26, 2016 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rohanorton/defef91f6431064ded7b to your computer and use it in GitHub Desktop.
Save rohanorton/defef91f6431064ded7b to your computer and use it in GitHub Desktop.
Partial
const partial = (fn, oldArgs = []) => (...newArgs) => {
const totalNumberOfArgsRequired = fn.length;
const args = oldArgs.concat(newArgs);
const numberOfRemainingArgs = totalNumberOfArgsRequired - args.length;
return (numberOfRemainingArgs > 0) ?
partial(fn, args) :
fn(...args);
}
export default partial;
/*globals describe, it */
import partial from '../partial';
import assert from 'assert';
describe('partial()', () => {
it('partially applies argument', () => {
const add = (a, b) => a + b;
const addThree = partial(add)(3);
const expected = add(3, 7);
const actual = addThree(7)
assert.equal(actual, expected);
});
it('curries a function', () => {
const add = (a, b, c, d) => a + b + c + d;
const partialAdd = partial(add);
const expected = add(1, 2, 3, 4);
const actual = partialAdd(1)(2)(3)(4)
assert.equal(actual, expected);
});
it('works more than once', () => {
const add = (a, b, c, d) => a + b + c + d;
const partialAddOne = partial(add)(1);
const actualOne = partialAddOne(2, 3, 4);
const actualTwo = partialAddOne(1, 1, 1);
const expectedOne = add(1, 2, 3, 4);
const expectedTwo = add(1, 1, 1, 1);
assert.equal(actualOne, expectedOne);
assert.equal(actualTwo, expectedTwo);
});
it('allows function with no arguments', () => {
const noArgs = () => 15;
const partialNoArgs = partial(noArgs);
const expected = noArgs();
const actual = partialNoArgs()
assert.equal(actual, expected);
});
it('still works when invoked upon already partially applied functions', () => {
const add = (a, b, c, d) => a + b + c + d;
const partialAdd = partial(add);
const partialPartialAdd = partial(partialAdd);
const expected = add(1, 2, 3, 4);
const actual = partialPartialAdd(1)(2)(3)(4)
assert.equal(actual, expected);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment