Is there any way we can create a very generic function that supports all arguments?
function memoize(expensivefn) {
const map = new Map();
// args can have array, object, functions and any other data types
return function(...args) {
if (map.has(args)) return map.get(args);
const result = expensivefn(...args);
map.set(args, result);
return result;
};
}
const expensiveFunction = args => {
console.log("A very expensive function, can block the tread!");
};
const memfun = memoize(expensiveFunction);
// calling function with named function
function add(a, b) {
return a + b;
}
memfun(add); // invoke the expensive function
memfun(add); // return from cache
// calling function with anonymous function
memfun(() => {
console.log("print someting!");
}); // invoke the expensive function
memfun(() => {
console.log("print someting!");
}); // return from cache
// Calling function with array and object
memfun([1, 2, 4, 4], { name: "abc" }); // invoke the expensive function
memfun([1, 2, 4, 4], { name: "abc" }); // return from cache