Skip to content

Instantly share code, notes, and snippets.

@Quaese
Created October 15, 2022 14:04
Show Gist options
  • Select an option

  • Save Quaese/21e86cc274ea9594113333e4c38a084f to your computer and use it in GitHub Desktop.

Select an option

Save Quaese/21e86cc274ea9594113333e4c38a084f to your computer and use it in GitHub Desktop.
Memoize function for various arguments
const memoize = function (func) {
const hashCode = function (value) {
var hash = 0,
i,
chr,
len;
try {
value = JSON.stringify(value);
} catch (e) {
value = value.toString();
}
if (value.length === 0) {
return hash;
}
for (i = 0, len = value.length; i < len; i++) {
chr = value.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
let memo = new Map();
return function () {
// let key = Array.from(arguments).reduce(
// (accu, curr) => { console.log(curr, ": ", hashCode(curr)); return accu + "," + hashCode(curr);},
// ""
// );
let key = Array.from(arguments).map(
(val) => hashCode(val)
).join(",");
// return cached value if exists
if (memo.has(key)) {
return memo.get(key);
}
// call function
let result = func.apply(this, arguments);
//
memo.set(key, result);
return result;
};
};
/*
// Examples
let addObj = (o, p) => o.v + p.v;
addObj = memoize(addObj);
addObj({v: 2}, {v: 6});
let addArr = (u, v) => u[0] + v[0];
addArr = memoize(addArr);
addArr([2], [6]);
let add = (a, b) => a + b;
add = memoize(add);
add(2, 3);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment