Last active
February 26, 2016 13:29
-
-
Save rohanorton/defef91f6431064ded7b to your computer and use it in GitHub Desktop.
Partial
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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