Created
October 11, 2017 06:45
-
-
Save cmstead/8cea764af0d1bc6b803bd7c22ca44a06 to your computer and use it in GitHub Desktop.
Lazy ID with memoization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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