Skip to content

Commit

Permalink
✨ PoC on new currying (#298)
Browse files Browse the repository at this point in the history
**Issue :** fix #297
  • Loading branch information
nlepage committed Jan 22, 2019
1 parent 2debf64 commit 0d23195
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
17 changes: 17 additions & 0 deletions packages/immutadot/src/core/curry.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export function curry(fn, minArity = fn.length) {
function curried(prevArgs) {
return (...args) => {
if (prevArgs.length >= minArity - 1)
return fn(args[0], ...prevArgs)

return curried(prevArgs.concat(args))
}
}

return (...args) => {
if (args.length >= minArity)
return fn(...args)

return curried(args)
}
}
28 changes: 28 additions & 0 deletions packages/immutadot/src/core/curry.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/* eslint-env jest */
import { curry } from './curry'

describe('curry.curry', () => {
function fill(obj, path, value, start = 0, end = -1, extraArg) {
return `fill(${obj}, ${path}, ${value}, ${start}, ${end}, ${extraArg})`
}
const curriedFill = curry(fill)

it('should allow non curried calls', () => {
expect(curriedFill('obj', 'path', 'value')).toBe('fill(obj, path, value, 0, -1, undefined)')
expect(curriedFill('obj', 'path', 'value', 1)).toBe('fill(obj, path, value, 1, -1, undefined)')
expect(curriedFill('obj', 'path', 'value', 1, 2)).toBe('fill(obj, path, value, 1, 2, undefined)')
expect(curriedFill('obj', 'path', 'value', 1, 2, 'extraArg')).toBe('fill(obj, path, value, 1, 2, extraArg)')
})

it('should allow all sorts of curried calls', () => {
expect(curriedFill('path', 'value')('obj')).toBe('fill(obj, path, value, 0, -1, undefined)')
expect(curriedFill('path')('value')('obj')).toBe('fill(obj, path, value, 0, -1, undefined)')
expect(curriedFill('path')('value', 1)('obj')).toBe('fill(obj, path, value, 1, -1, undefined)')
expect(curriedFill('path')('value', 1, 2)('obj')).toBe('fill(obj, path, value, 1, 2, undefined)')
expect(curriedFill('path')('value', 1, 2, 'extraArg')('obj')).toBe('fill(obj, path, value, 1, 2, extraArg)')
})

it('should discard extra args in last curried call', () => {
expect(curriedFill('path', 'value')('obj', 'extraArg')).toBe('fill(obj, path, value, 0, -1, undefined)')
})
})

0 comments on commit 0d23195

Please sign in to comment.