Skip to content

Instantly share code, notes, and snippets.

@zspecza
Last active December 6, 2016 02:29
Show Gist options
  • Save zspecza/d73542dec4e5fc105f521771ce2349cb to your computer and use it in GitHub Desktop.
Save zspecza/d73542dec4e5fc105f521771ce2349cb to your computer and use it in GitHub Desktop.
sets the length property of a given function to the given arity
function setArity (arity, fn) {
if (typeof setArity.cache === 'undefined') {
setArity.cache = {}
}
if (typeof setArity.cache[arity] === 'undefined') {
setArity.cache[arity] = (fn) => {
switch (arity) {
case 0: return function () { return fn.apply(this, arguments) }
case 1: return function (a) { return fn.apply(this, arguments) }
case 2: return function (a, b) { return fn.apply(this, arguments) }
case 3: return function (a, b, c) { return fn.apply(this, arguments) }
case 4: return function (a, b, c, d) { return fn.apply(this, arguments) }
case 5: return function (a, b, c, d, e) { return fn.apply(this, arguments) }
case 6: return function (a, b, c, d, e, f) { return fn.apply(this, arguments) }
case 7: return function (a, b, c, d, e, f, g) { return fn.apply(this, arguments) }
case 8: return function (a, b, c, d, e, f, g, h) { return fn.apply(this, arguments) }
case 9: return function (a, b, c, d, e, f, g, h, i) { return fn.apply(this, arguments) }
case 10: return function (a, b, c, d, e, f, g, h, i, j) { return fn.apply(this, arguments) }
default:
try {
const proxy = function () { return fn.apply(this, arguments) }
Object.defineProperty(proxy, 'length', { value: arity })
return proxy
} catch (e) {
const params = Array(arity).join(', _').substr(2)
const proxy = new Function(
'fn',
`return function (${params}) { return fn.apply(this, arguments); }`
)
return proxy(fn)
}
}
}
}
return setArity.cache[arity](fn)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment