Quick log of a refactoring pattern I've been using lately. Function.bind lets you curry methods, which is useful for throwing in more parameters to functions called outside of your control, like in functional Array methods or callbacks.
For instance:
window.setTimeout(function() {
foo.bar(baz);
}, 10);
Can be expressed as
window.setTimeout(foo.bar.bind(foo, baz)), 10);
Similarly in iterator methods if you need another argument to a mapper, for instance:
var howManyToAdd = 3;
[1, 2, 3].map(function(item) {
return item + howManyToAdd;
});
You can generalize this with a closure like
function adderMaker(howManyToAdd) {
return function(item) {
return item + howManyToAdd;
};
}
[1, 2, 3].map(adderMaker(3));
But simplify that more with bind:
function add(howManyToAdd, item) {
return item + howManyToAdd;
}
[1, 2, 3].map(add.bind(null, 3));