-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcurry.js
More file actions
28 lines (23 loc) · 1.08 KB
/
curry.js
File metadata and controls
28 lines (23 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Curries function to a fixed arity
export const curryN = (n, fn) =>
function curried(...args) {
const haveEnoughArgs = args.length >= n
const partiallyApplied = (...moreArgs) => curried(...args.concat(moreArgs))
if (haveEnoughArgs) return fn(...args)
return partiallyApplied
}
// Regular curry is just a special case of curryN, where n = function's arity
export const curry = (fn) => curryN(fn.length, fn)
// CurryV is a enhanced version of curry. Supports termination (early value return) through empty argument call
export const curryV = (fn) =>
function curried(...args) {
let shouldRunRightNow = args.length === 0
const haveEnoughArgs = args.length >= fn.length
const partiallyApplied = (...moreArgs) => {
shouldRunRightNow = moreArgs.length === 0
if (shouldRunRightNow) return fn(...args)
return curried(...args.concat(moreArgs))
}
if (haveEnoughArgs || shouldRunRightNow) return fn(...args)
return partiallyApplied
}