PROGRAMMING LANGUAGES

javascript memoization example – Tech Incent





If you’re looking to implement memorization in JavaScript, you’re likely referring to memoization, which is a technique used to optimize functions by caching their results based on their input parameters. This can help avoid unnecessary computations and improve the performance of your code

// Example of higher order function
// Memorization

/*
Callback function for reduce
*/
function reduceCallback(sum, element) {
  return sum + element
}

const total =  function(...circle) {
  const _total =  circle.reduce(reduceCallback)
  return _total;
};

// console.log(total(...radius))

// Higher Order Function
const higherOrderFunction = function (func) {
  const cache = {};
  
  return function(...circle) {
    const s = JSON.stringify(circle);
    if (cache[s]) {
      return cache[s]
    } else {
      const total = func(...circle)
      circle[s] = total
      return total
    }
  }
}

const calculator = higherOrderFunction(total)

console.time()
console.log(calculator(12, 13))
console.timeEnd()
console.time()
console.log(calculator(12, 13))
console.timeEnd()
console.time()
console.log(calculator(12, 13))
console.timeEnd()

25 // calculate
default: 2.06ms
25 // from cache
default: 0.054ms
25 // from cache
default: 0.037ms



sajal-avatar
Sajal Mia


Hey there, I am a passionate software engineer, blogger, researcher. I have worked with amazing companies. Nowadays I am working with Cloud base PAAS products. My expertise tech stack JavasScript, Node, Express, Angular, React, Python, Django. Most of my free time I am trying to write blogs to help other developers



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button