Skip to content

Instantly share code, notes, and snippets.

@branneman branneman/curry.js
Last active Jun 7, 2019

Embed
What would you like to do?
Higher order auto curry function
const curryN = (fn, arity, accIn = []) => (...args) => {
const len = args.length
const accOut = accIn.concat(args)
if (len + accIn.length >= arity) {
return fn.apply(this, accOut)
}
return curryN(fn, arity, accOut)
}
const curry = fn => curryN(fn, fn.length)
module.exports = { curryN, curry }
const { curryN, curry } = require('./curry')
describe('curryN()', () => {
const { curryN } = factory()
it('should correctly curry to given arity', () => {
const threeArgs = (a, b, c = 42) => c
const fn = curryN(threeArgs, 2)
const res1 = fn() //=> fn with arity of 2
const res2 = fn(1) //=> fn with arity of 1
const res3 = fn(1, 2) //=> run function
const res4 = fn(1, 2, 3) //=> run function
const res5 = fn(1, 2, 3, 4) //=> run function
expect(typeof res1).toStrictEqual('function')
expect(typeof res2).toStrictEqual('function')
expect(res3).toStrictEqual(42)
expect(res4).toStrictEqual(3)
expect(res5).toStrictEqual(3)
})
})
describe('curry()', () => {
it('accepts an arity of 0', () => {
const give15 = () => 10 + 5
const fn = curry(give15)
expect(fn()).toStrictEqual(15)
})
it('accepts an arity of 1', () => {
const add5 = n => n + 5
const fn = curry(add5)
expect(fn(10)).toStrictEqual(15)
})
it('accepts an arity of 2', () => {
const sum = (a, b) => a + b
const fn = curry(sum)
const result = [fn(10)(5), fn(10, 5)]
expect(result).toStrictEqual([15, 15])
})
it('accepts an arity of 3', () => {
const sum3 = (a, b, c) => a + b + c
const fn = curry(sum3)
const result = [
fn(10, 20, 30),
fn(10)(20, 30),
fn(10, 20)(30),
fn(10)(20)(30)
]
expect(result).toStrictEqual([60, 60, 60, 60])
})
it('accepts an arity of 12', () => {
const sum12 = (a, b, c, d, e, f, g, h, i, j, k, l) =>
a + b + c + d + e + f + g + h + i + j + k + l
const fn = curry(sum12)
const result = [
fn(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
fn(1, 2)(3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
fn(1, 2, 3, 4, 5, 6)(7)(8)(9, 10, 11, 12),
fn(1, 2)(3, 4)(5, 6, 7, 8)(9, 10, 11, 12),
fn(1)(2)(3)(4)(5)(6)(7)(8)(9)(10)(11)(12)
]
expect(result).toStrictEqual([78, 78, 78, 78, 78])
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.