Skip to content

Instantly share code, notes, and snippets.

@cmstead
Created October 11, 2017 06:45
Show Gist options
  • Save cmstead/8cea764af0d1bc6b803bd7c22ca44a06 to your computer and use it in GitHub Desktop.
Save cmstead/8cea764af0d1bc6b803bd7c22ca44a06 to your computer and use it in GitHub Desktop.
Lazy ID with memoization
const nullFn = (fn) => typeof fn === 'function' ? fn : () => null;
function dict(key, value, struct) {
return (function (localStruct) {
return (ref) => ref === key ? value : localStruct(ref)
})(nullFn(struct));
}
function memoize(fn) {
let store = null;
return function (value) {
const storedResult = store !== null ? store(value) : null;
const result = storedResult !== null ? storedResult : fn(value);
store = storedResult !== null ? store : dict(value, result, store);
return result;
}
}
const getUniqueId = (function () {
let currentId = 0;
return () => currentId++;
})()
const getId = (function (getId) {
return function () {
return getId(this);
}
})(memoize(getUniqueId));
function setLazyId(obj) {
return Object.defineProperty(obj, 'id', {
get: getId
});
}
const myObj = setLazyId({});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment