Wrap a function so it reports a custom length property
Every JavaScript function has a length property: the number of parameters it expects. Libraries rely on it. A curry helper uses it to decide when enough arguments have arrived, and Express tells error middleware apart from normal middleware by checking for a length of 4.
The trouble starts when you wrap a function. A logging or timing wrapper written as (...args) => fn(...args) has a length of 0, so curry and Express silently stop working.
Implement withArity(fn, length). It returns a new function that behaves exactly like fn but reports the given length.
withArity(fn, length?) // => wrapper function
length is countedfunction (a, b = 1, c) {} has length 1; (...args) => {} has length 0.({ id }, [first]) => {} has length 2.fn.length = 3) does not change it.fn with the same this and all the arguments it received (even more than length), and returns whatever fn returns. Errors thrown by fn propagate.wrapper.length equals length. If length is omitted (undefined), use fn.length.length property has the same attributes as a native one: not writable, not enumerable, configurable.wrapper.name equals fn.name.fn itself is not modified.TypeError if fn is not a function, and a RangeError if length is given but is not a non-negative integer (for example -1, 1.5, NaN or '2').function addPrice(base, tax, shipping) {
return base + tax + shipping;
}
const logged = (...args) => addPrice(...args);
logged.length; // => 0 (curry would call it immediately)
const safe = withArity((...args) => addPrice(...args), addPrice.length);
safe.length; // => 3
safe(10, 2, 5); // => 17
withArity(function handler(err, req, res, next) {}).length; // => 4
withArity(function handler() {}, 2).name; // => 'handler'
withArity('nope'); // throws TypeError
withArity(addPrice, -1); // throws RangeError