curry-arity
Simple, tiny curry() and curryN() functions.
Both can take functions of any arity, there are no limits.
Resulting functions will always have the correct arity (length
property).
This library does not use eval(), new Function() or any dynamic code evaluation.
Examples
const f = a + b + c; const add = ; addlength; // 3length; // 220length; // 1 2030; // 6030; // 6020 30; // 60; // 60 /* reusable */const addTen = ; 30; // 6050; // 100
Only the parameters before the first one with a default value are counted:
const add = ; addlength; // 220; // 60// add(10)(20)(70) would throw TypeError /* you can pass additional arguments in the final call */20 70; // 100
You can also specify arity using curryN()
instead of curry()
:
const add = ; addlength; // 32070; // 100 /* undefined always triggers the default value */20undefined; // 60
Another example with curryN()
:
const add = args; length; // 21020; // 30 length; // 3102070; // 100
Curried functions also correctly handle implicit this
:
const obj = a: 10 addMe: /* 'this' from the first call (obj.addMe(20)) is always used */obj30; // 60
How it works
Using Object.defineProperty()
on created function objects. The original function object is not changed in any way.
By the ES6 specification, function.length
is configurable. It wasn't configurable in ES5.
Supported Environments
This library will not work in old ES5 browsers, namely IE11. By design, functions will throw if the length cannot be set, as the correct arity is a part of the API.
The code is not transpiled to ES5, as the ES6 version is more efficient and the library wouldn't work in all ES5 browsers anyway. So, supported environments are:
- Node >= 6
- Browsers that support basic ES6 syntax
Installation and Usage
Node
$ npm install curry-arity
const curry curryN = ; const f = a + b + c; const fc = ;console; // 60 const fc3 = ;console; // 100
Browser Script
Unminified (~600B):
or
Minified (~250B):
or
The script creates a global variable CurryArity
:
const f = a + b + c; const fc = CurryArity;console; // 60 const fc3 = CurryArity;console; // 100
You can also install the package and take the scripts from the dist
folder.
ES Module
$ npm install curry-arity
ES module: ./node_modules/curry-arity/src/index.js
If you are using Webpack, Rollup or any tool that reads from pkg.module
, then simply:
; const f = a + b + c; const fc = ;const fc3 = ;
and it will use the ES module directly, instead of the CommonJS version.
API
curry(f)
Returns curried f, with the original arity.
f
Function of any arity.
curryN(n, f)
Returns curried f, with the specified arity.
n
Arity of the resulting function. Should be a non-negative integer.
It can be less, equal or greater than the original arity.
f
Function of any arity.
By design, the functions do not validate provided arguments.