Cube

 //caching


//addition , a+b+c  add(2,3)

// sum operation is a heavy operator 


const sortedString=(arr)=>{

  const sort = arr.sort((a,b)=>a-b)

  return sort.join('').toString()

}

let cache ={};

const add = (...allVal)=>{


  //look for the value exist or not

  if(cache[sortedString(allVal)]){

      console.log('from cache')

    return cache[sortedString(allVal)]

  }

  else{

    const sum = allVal.reduce((acc,curr)=>{

    acc+=curr;

    return acc;

  },0)

  cache[sortedString(allVal)]=sum;

  console.log('from computation')

  return sum;

  }

}


console.log(add(2,3,4,5))

console.log(add(2,3,4,5))






// let cache={

//   '2':5, 

//   '32':5

// }

// console.log(cache['23']|| cache['32'])



FIXED LOGIC

const sortedString = (arr) => {

  return arr.sort((a, b) => a - b).join(',');

};


let cache = {};


const add = (...allVal) => {

  const key = sortedString(allVal);


  if (cache[key]) {

    console.log('from cache');

    return cache[key];

  } else {

    const sum = allVal.reduce((acc, curr) => {

      acc += curr;

      return acc;

    }, 0);


    cache[key] = sum;

    console.log('from computation');

    return sum;

  }

};


console.log(add(2, 3, 4, 5));

console.log(add(2, 3, 4, 5));


Throttling, Virtual DOM should be slow , 

critical rendering path

Comments

Popular posts from this blog

TO the new

4048