What is arity-n?
The arity-n package is designed to help with function arity, specifically allowing you to create functions of any arity based on a single function. This can be particularly useful for currying and partial application patterns, where the number of arguments a function takes is important for its execution.
What are arity-n's main functionalities?
Creating fixed arity functions
This feature allows you to create a new function with a fixed number of arguments (arity) from an existing function. In the example, `arityN` is used to ensure the `sum` function strictly accepts two arguments.
const { arityN } = require('arity-n');
const sum = (a, b) => a + b;
const sumFixed = arityN(2, sum);
console.log(sumFixed(1, 2)); // Outputs: 3
Currying functions with specific arity
This demonstrates how to curry a function to a specific arity using `curryN`. The `add` function is transformed into a curried version that requires exactly three arguments, provided one at a time.
const { curryN } = require('arity-n');
const add = (a, b, c) => a + b + c;
const curriedAdd = curryN(3, add);
console.log(curriedAdd(1)(2)(3)); // Outputs: 6
Other packages similar to arity-n
lodash
Lodash is a comprehensive utility library that offers similar functionalities through methods like `_.curry` which can be used for currying functions. However, lodash is much larger and provides a wide range of utilities beyond function arity manipulation.
ramda
Ramda is a functional programming library that emphasizes a more functional approach than arity-n. It includes `R.curry`, which automatically curries a function, similar to `curryN` in arity-n. Ramda offers a broader set of functional programming utilities, making it more versatile but also more complex.
arity-n
Wraps a function with a function of a sertain arity.
Installation
npm install arity-n
Usage
function fn(a, b, c, d) {
}
var arityN = require('arity-n');
var newFn = arityN(fn, 3);
newFn.length;
var arity4 = require('arity-n/4');
var newFn = arity4(fn);
newFn.length;
var newFn = arityN(fn, 7);
newFn.length;