Skip to content

@Gozala /defn.js
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
No more Array.prototype.slice.call please!!
/* vim:set ts=2 sw=2 sts=2 expandtab */
/*jshint asi: true undef: true es5: true node: true devel: true
forin: false latedef: false */
/*global define: true */
function defn(name) {
var delegee, delegees = {}, lambdas = Array.prototype.slice.call(arguments, 1)
// Use last delegee as a default one
var defaultDelegee = lambdas.pop()
// Store delegees in map associated by number of arguments they take.
while ((delegee = lambdas.shift())) delegees[delegee.length] = delegee
function fn() {
var args = arguments, delegee = delegees[arguments.length]
if (!delegee) {
delegee = defaultDelegee
// Construct array of arguments that includes every that follows the last
// expected one. So that last argument is an array of all rest arguments.
args = Array.prototype.slice.call(args)
args.push(args.splice(delegee.length - 1, args.length))
}
return delegee.apply(this, args)
}
fn.displayName = name
return fn
}
/* vim:set ts=2 sw=2 sts=2 expandtab */
/*jshint asi: true undef: true es5: true node: true devel: true
forin: false latedef: false */
/*global define: true */
var multiply = defn('multiply', function(args) {
return args.reduce(function(a, b) {
return a * b
}, 1)
})
multiply(2, 3, 7) // => 42
// Micro optimizations for special cases.
var sum = defn('sum',
function(a) { return a },
function(a, b) { return a + b },
function(a, b, c) { return a + b + c },
function(a, rest) { return rest.reduce(function(a, b) { return a + b }, a) })
sum(1) // => 1
sum(1, 2) // => 3
sum(1, 2, 3) // => 6
sum(1, 2, 3, 4, 5) // => 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.