Created
January 20, 2020 23:48
-
-
Save nestoralonso/b41387c6b3a922779e8f345a2e4c9d25 to your computer and use it in GitHub Desktop.
Memoize High Order Function that can handle multiple and nested arguments
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
function equals(a, b) { | |
if (a === b) return true; | |
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime(); | |
if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b; | |
if (a.prototype !== b.prototype) return false; | |
const keys = Object.keys(a); | |
if (keys.length !== Object.keys(b).length) return false; | |
return keys.every(k => equals(a[k], b[k])); | |
}; | |
function memoizer(fun) { | |
var pastArgs = new Set(); | |
function getArgsKey(args = []) { | |
for (const k of pastArgs.keys()) { | |
if (equals(args, k)) return k; | |
} | |
pastArgs.add(args); | |
return args; | |
} | |
let cache = new Map(); | |
return function (...args) { | |
const argsKey = getArgsKey(args); | |
if (cache.get(argsKey) !== undefined) { | |
return cache.get(argsKey); | |
} else { | |
const result = fun(...args) | |
cache.set(argsKey, result); | |
return result | |
} | |
} | |
} | |
var add = (x, y) => console.log(`adding ${x} and ${y}`) || x + y; | |
var cachedAdd = memoizer(add); | |
console.log(cachedAdd(1, 2)) | |
console.log(cachedAdd(1, 2)) | |
var getProp = (o, k) => console.log(`computing getProp with ${k}`) || o[k]; | |
var cachedGetProp = memoizer(getProp); | |
console.log(cachedGetProp({ name: 'Felix' }, 'name')) | |
console.log(cachedGetProp({ name: 'Felix' }, 'name')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment