krishna chaitanya
Krishna Vulchi's Blog


Krishna Vulchi's Blog



krishna chaitanya's photo
krishna chaitanya
·Feb 5, 2023·

2 min read

Memoization is a technique to make function calls in an optimized way that has the heavy computational process

It Caches the result as a key and value, Next time on calling the function it checks with the key, If the key is already present it returns the value from the cache else it does the computation process and stores it in the cache

We will learn memoization with an example problem

Problem Statement:

Write a memoize function that takes a callback.

The memoize function will return a memoized version of the callback function

All of the return values of the memoized function are cached. If the memoized callback is called with an existing cache key (defined below), then that cached value is returned without invoking the callback again.

The memoized function should also have 3 methods

  • has(...params): returns true if the cache has a key of the corresponding params

  • delete(.params): delete the cache

  • clear(): clear the cache


function memoize(callback) {

  let cache = new Map() 
// if object is taken it will constrant to only strings

  function getCacheKey(params) {
    return JSON.stringify(args)

  const memoized = function(...params) {
    const cacheKey = getCacheKey(params)

    if(cache.has(cacheKey)) {
      return cache.get(cacheKey)
    const output = callback(...params)
    cache.set(cacheKey, output)
    return output

  memoized.clear = function () {

  memoized.delete = function (...params) {
    const cacheKey = getCacheKey(params)

  memoized.has = function (...params) {
    const cacheKey = getCacheKey(params)
    return cache.has(cacheKey)
  return memoized;

const getSquare = (a) => a * a

const memo = memoize(getSquare)
memo(2) // calls getSquare callback
memo(3) // calls getSquare callback
memo(2) // return from cache
memo(5) // call getSquare callback
memo(5) // return from cache
memo.has(5) // true
memo.has(6) // false
memo.delete(5) // deletes 5 params details
memo.has(5) // false

memoized method checks if the args are in the cache or not

getCacheKey // returns the params in JSON.stringify to store it as key

memoized.delete deletes the passed params

memoized.has returns the boolean value based on availability in cache

memoized.clear clears all the params

Thanks for reading :)

Share this