3 ms·
function butter (){
by escape_goat 12y ago
function butter (){
fn=arguments[0];
return function(){
var args = [];
for( var n=1; n<arguments.length; n++ ) {
args.push(arguments[n]);
};
return fn.apply(this,args)
}
}
edit: I know my loop is totally anachronistic, but I'm short on time for testing this.
- aaronem 12y agofunction butter(fun, count) { count = count || 1; if (count < 1) { throw new Error('Can't butter no toast'); } return function() { return fun.apply(this, Array.prototype.slice.call(arguments, 0, count)); } }
- escape_goat 12y agoThis is a dumb question, but I feel like maybe I'm failing to pick up on something with respect to the necessity of the count parameter. It doesn't seem like it should be necessary, but both 'butt' and your version here use it. What is it for?
- aaronem 12y agoIt specifies how many arguments the returned function should take; in my implementation, it defaults to 1 (so you can use it like "but"), but accepts other values (so you can use it like "butt"). The reason why it's necessary to specify how many arguments are of interest is because Of course, since this is just common or garden partial application in a language with first-class functions and a liberal attitude toward signatures, it could be trivially generalized thus: function partial(fun) { var applied = Array.prototype.slice.call(arguments, 1); return function() { var args = applied // clone the already applied args, so we don't mistakenly modify when we... .slice() // ...tack on the args we received in this function's call .concat(Array.prototype.slice.call(arguments)); return fun.apply(this, args); }; } var addThreeNumbers = function(a, b, c) { return a + b + c; }; var onePlusTheseTwo = partial(addThreeNumbers, 1); var threePlusThisOne = partial(onePlusTheseTwo, 2); assert(addThreeNumbers(1, 2, 3) === 6); assert(onePlusTheseTwo(2, 3) === 6); assert(threePlusThisOne(3) === 6); // -> all true It only looks like wizardry if you're not used to dealing with higher-order functions, wherein I think is meant to lie the joke, if any.
- escape_goat 12y agoI don't encounter higher-order functions very often, and I certainly am not mentally flexible with them. Nonetheless, I have heard of partial application, yes. I understood what the count parameter was doing. What I was having trouble understanding was why it was being used; specifically, why 'but' would have a strict arity of one in the first place, and why a second function (specifying arity) would be necessary. It doesn't follow very clearly from the examples given at all. edit: ...was this whole thing actually a joke? I thought he was serious.