DEV Community

StormyTalent
StormyTalent

Posted on

Simple way to Implement JS Cache using Closure. (JS developer need to know)

In React, there are some functionality for cache using React hooks such as React.memo, useCallback, useMemo and so on.
In this time, we try to implement those cache action using closure in JS(ES6+).
Closure means the lexical context a function was declared in and the variables it has access to.

function fnGenerator(str) {
  const strLog = 'The string I was given is "' + str + '"';
  return function() {
    console.log(strLog);
  }
}
const fnRet = fnGenerator("BatMan");
fnRet();  // -> The string I was give is "BatMan"
Enter fullscreen mode Exit fullscreen mode

To engage this theory, we can implement Cache functionality in JS.
Here is an example I did for fibonacci.

const originalFibo = (n) => {
  let res = [1, 1];
  if (res.length >= n )
    return res;
  while(res.length <= n)
    res.push(res[res.length - 1] + res[res.length - 2]);
  return res;  
}

const fbGenerator = (n) => {
  let res = [1, 1];
  return function() {
    if (res.length >= n)
     return res;
    while(res.length <= n)
       res.push(res[res.length - 1] + res[res.length - 2]);
    return res;
  }
}

const fibo = fbGenerator(100);
console.time('cache started');
for(let i = 0; i < 1000; i++)
  fibo();
console.timeEnd('cache ended');

console.time('original started');
for(let i = 0; i < 1000; i++)
  originalFibo(100);
console.timeEnd('original ended');
Enter fullscreen mode Exit fullscreen mode

You will notice that this code snap dramatically decreases the runtime compared to original codesnap.

Top comments (0)