public
Created

No more Array.prototype.slice.call please!!

  • Download Gist
defn.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/* 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
}
usage.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/* 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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.