0.2.0 • Published 2 years ago

bind.for v0.2.0

Weekly downloads
3
License
ISC
Repository
github
Last release
2 years ago

bind.for

Build Status Coverage Status

A lazy Function.prototype.for(context) bind helper.

This is an alternative take at the same problem bound-once would like to solve, except this should perform better for the following reasons:

  • the WeakMap is lazily created once per each method
  • because it's usually the method that binds multiple contexts, and not the other way around, this approach requires less moving parts
  • bound-once looks up for the method, either as function or as a string, then it weakly refers the context to a new Map, if not previously referenced, then it performs a lookup via such map to return the bound method, or it stores it in there once and return. bind.for here, looks up for the context right away, and it stores once the bind of itself if the content wasn't previously stored. This is one operation instead of 3.

By default, this module pollutes the Function.prototype with a lazy for method, but if that's not your cup of tea, you can include the ponyfill instead.

// global Function.prototype pollution
import 'bind.for';

const context = {};

method.for(context) === method.for(context);
method.for(context)() === context;

function method() {
  return this;
}

// clean ponyfill
import bindFor from 'bind.for/pony';

// will add the lazy `for` method
const fn = bindFor(function () { return this; });
fn.for(context) === fn.for(context);
0.2.0

2 years ago

0.1.1

4 years ago

0.1.0

4 years ago

0.0.0

4 years ago