Skip to content

Instantly share code, notes, and snippets.

@rmg
Last active July 6, 2016 02:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmg/33951df13f64e224b9f73cf693fb6274 to your computer and use it in GitHub Desktop.
Save rmg/33951df13f64e224b9f73cf693fb6274 to your computer and use it in GitHub Desktop.
JS bind operator

Idea:

A simple shorthand for foo.bar.bind(foo, ...) to make it nicer to work with partial function application.

// shorthand
function sillyClone(input) {
  var acc = [];
  input.forEach(acc.push&());
  return acc;
}
// expansion
function sillyClone(input) {
  var acc = [];
  input.forEach(acc.push.bind(acc));
  return acc;
}

More practical/realistic example:

var test = require('tap').test;
var mod = require('../'); // whatever our module is...

test('simple calls', function(t) {
  t.throws(mod&(1), MissingArgumentError);
  t.throws(mod&(1, 2, 3, 4), TooManyArgumentsError);
  t.doesNotThrow(mod&(1, 2, 3), 'just right');
  t.end();
});

test('cumbersome calls', function(t) {
  t.throws(mod.bind(null, 1), MissingArgumentError);
  t.throws(mod.bind(null, 1, 2, 3, 4), TooManyArgumentsError);
  t.doesNotThrow(mod.bind(null, 1, 2, 3), 'just right');
  t.end();
});

test('arrows', function(t) {
  t.throws(()=>{mod(1)}, MissingArgumentError);
  t.throws(()=>{mod(1, 2, 3, 4)}, TooManyArgumentsError);
  t.doesNotThrow(()=>{mod(1, 2, 3)}, 'just right');
  t.end();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment