1// a simple pure function to get a value adding 10
2const add = (n) => (n + 10);
3console.log('Simple call', add(3));
4// a simple memoize function that takes in a function
5// and returns a memoized function
6const memoize = (fn) => {
7 let cache = {};
8 return (...args) => {
9 let n = args[0]; // just taking one argument here
10 if (n in cache) {
11 console.log('Fetching from cache');
12 return cache[n];
13 }
14 else {
15 console.log('Calculating result');
16 let result = fn(n);
17 cache[n] = result;
18 return result;
19 }
20 }
21}
22// creating a memoized function for the 'add' pure function
23const memoizedAdd = memoize(add);
24console.log(memoizedAdd(3)); // calculated
25console.log(memoizedAdd(3)); // cached
26console.log(memoizedAdd(4)); // calculated
27console.log(memoizedAdd(4)); // cached