11 points · by bevacqua · 11y ago · 20 comments
var butt = require('butt');
var but = function(fun) {
return butt(fun, 1);
};
or even var but = function(fun) {
return function(arg) {
return fun(arg);
};
}; module.exports = function (fn) {
return function (first) {
fn(first);
};
}; n.forEach(console.log);
Just tested on Chrome, it gives me an error TypeError: Illegal invocation n.forEach(console.log.bind(console));
I don't think there's any reason for this library to exist after you understand `this` semantics but I may be missing something.e: was, in fact, missing something. Apologies for the disparaging comment, see replies.
[1, 2, 3].forEach(console.log.bind(console));
> 1 0 [1, 2, 3]
> 2 1 [1, 2, 3]
> 3 2 [1, 2, 3] n.forEach(console.log.bind(console));
forEach is passing console all of its callback arguments, resulting in logging of keys, values, and array.EDIT: Forgot array
n.forEach(console.log);
Works on firefox. Chrome treats console.log differently from other functions for reasons unknown.but really, this library has no reason to exist
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. function 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));
}
}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.