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
1const memoizedValue = [];
2const clumsysquare = (num) => {
3 if ((memoizedValue[num] == !undefined)) {
4 return memoizedValue[num];
5 }
6
7 let result = 0;
8 for (let i = 1; i <= num; i++) {
9 for (let j = 1; j <= num; j++) {
10 result++;
11 }
12 }
13
14 memoizedValue[num] = result;
15 return result;
16};
17
18console.log(clumsysquare(190));
19console.log(clumsysquare(799));
20console.log(clumsysquare(4000));
21console.log(clumsysquare(7467));
22console.log(clumsysquare(9666));
23