Tech Incent
Javascript

javascript memoization example

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

Related posts

Explained RxJs switchMap operator with example

Sajal Mia

Javascript string methods example

Sajal Mia

JS calculate the total number of elements in an array

Sajal Mia

Higher Order Function in javascript

Sajal Mia

Javascript array methods example

Sajal Mia

Pure function in javascript

Sajal Mia