Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created November 5, 2015 16:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmcw/61a3b5bafd4cbe0d9ee9 to your computer and use it in GitHub Desktop.
Save tmcw/61a3b5bafd4cbe0d9ee9 to your computer and use it in GitHub Desktop.

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));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment