@sanity/desk-tool
Version:
Tool for managing all sorts of content in a structured manner
31 lines (27 loc) • 906 B
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.memoBind = memoBind;
/* eslint-disable @typescript-eslint/ban-types */
// `WeakMap`s require the first type param to extend `object`
var bindCache = new WeakMap();
/**
* An alternative to `obj.method.bind(obj)` that utilizes a weakmap to return
* the same memory reference for sequent binds.
*/
function memoBind(obj, methodKey) {
var boundMethods = bindCache.get(obj) || new Map();
if (boundMethods) {
var _bound = boundMethods.get(methodKey);
if (_bound) return _bound;
}
var method = obj[methodKey];
if (typeof method !== 'function') {
throw new Error("Expected property `".concat(methodKey, "` to be a function but got ").concat(typeof method, " instead."));
}
var bound = method.bind(obj);
boundMethods.set(methodKey, bound);
bindCache.set(obj, boundMethods);
return bound;
}