Skip to content
This repository was archived by the owner on Feb 20, 2019. It is now read-only.

Commit 5af53e3

Browse files
ericArbourKent C. Dodds
authored andcommitted
feat(curry): add curry function with tests (#194)
I have added a new utility function that allows for the creation of a curried version of a function provided. I also added a basic test to verify that the function behaves as expected. Resolves #193
1 parent 18379d4 commit 5af53e3

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

src/curry.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
export default curry
2+
3+
/*
4+
* Original Source: https://stackoverflow.com/a/14045565/6121634
5+
* Updated to ES6 format to meet style guides via:
6+
* https://github.com/getify/Functional-Light-JS/blob/master/manuscript/ch3.md/#some-now-some-later
7+
*
8+
* This utility function takes a function as a parameter and returns a curried version of the function.
9+
*
10+
* @param {Function} func - The function to be curried
11+
* @return {Function} - The curried version of the initially provided function
12+
*/
13+
function curry(fn, arity = fn.length) {
14+
return (function nextCurried(prevArgs) {
15+
return function curried(nextArg) {
16+
const args = [...prevArgs, nextArg]
17+
18+
if (args.length >= arity) {
19+
return fn(...args)
20+
} else {
21+
return nextCurried(args)
22+
}
23+
}
24+
})([])
25+
}

src/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ import lcm from './lcm'
7070
import occurrences from './occurrences'
7171
import getMiddle from './getMiddle'
7272
import debounce from './debounce'
73+
import curry from './curry'
7374

7475
export {
7576
reverseArrayInPlace,
@@ -144,4 +145,5 @@ export {
144145
occurrences,
145146
getMiddle,
146147
debounce,
148+
curry,
147149
}

test/curry.test.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import test from 'ava'
2+
import {curry} from '../src'
3+
4+
test('Returns a curried version of the provided function', t => {
5+
function addOrConcat(one, two, three) {
6+
return one + two + three
7+
}
8+
const expected = addOrConcat('foo', 'bar', 'baz')
9+
const curried = curry(addOrConcat)
10+
const withFirstArg = curried('foo')
11+
const withSecondArg = withFirstArg('bar')
12+
const actual = withSecondArg('baz')
13+
t.deepEqual(actual, expected)
14+
})

0 commit comments

Comments
 (0)