Created
June 5, 2017 08:32
-
-
Save JasonHewison/0be4fc46df667f342242f8a96d1a7b17 to your computer and use it in GitHub Desktop.
TDD'd Currying
This file contains 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
export default function curry(func, ...args) { | |
function inner(currentArgs, ...newArgs) { | |
const currentLength = currentArgs.length + newArgs.length; | |
if (currentLength >= func.length) { | |
return func(...currentArgs, ...newArgs); | |
} else { | |
return (...furtherArgs) => | |
inner([...currentArgs, ...newArgs], ...furtherArgs); | |
} | |
} | |
return inner(args); | |
} |
This file contains 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
import curry from "./curry"; | |
function target(a, b, c) { | |
return a + b + c; | |
} | |
function target2(a, b, c, d, e) { | |
return a + b + c + d + e; | |
} | |
describe("unit: curry", () => { | |
let bob; | |
beforeEach(() => { | |
bob = curry(target); | |
}); | |
it("allows you to supply all arguments at once", () => { | |
expect(bob(1, 2, 3)).toBe(6); | |
expect(bob(3, 6, 9)).toBe(18); | |
}); | |
it("allows you to set initial args in the curry function", () => { | |
bob = curry(target, 1); | |
expect(bob(2, 3)).toBe(6); | |
expect(bob(3, 5)).toBe(9); | |
}); | |
it("allows you to supply all arguments seperately", () => { | |
expect(bob(1)(2)(3)).toBe(6); | |
expect(bob(3)(6)(9)).toBe(18); | |
}); | |
it("allows you to supply all arguments seperately with an initial curry", () => { | |
bob = curry(target, 1, 2); | |
expect(bob(3)).toBe(6); | |
expect(bob(9)).toBe(12); | |
bob = curry(target2, 1, 2); | |
expect(bob(3, 4, 5)).toBe(15); | |
expect(bob(9, 10, 11)).toBe(33); | |
}); | |
it("allows you to recurry", () => { | |
bob = curry(target2, 1, 2); | |
const bob2 = curry(bob, 3); | |
expect(bob2(4, 5)).toBe(15); | |
expect(curry(bob2, 9, 10)).toBe(25); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment