Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
Javascript Memoization Implementation

I've been debating this topic with my mates at work. I would like to know from you guys, if this is, actually, the right way of implementing the memoization.

function memoize(result) {
  let cache = {};

  return function() {
    if (cache[result]) {
      // returns cached result / no calculation
      return cache[result];
    }
    // calculating...
    cache[result] = result;
    return cache[result];
  };
}

function expensiveCalculation() {
  let counter = 0;
  for (let i = 0; i < 1000000; i++) {
    counter += i;
  }
  return counter;
}

console.time("FirstCalculation");
const memoizedExpensiveCalculation = memoize(expensiveCalculation());
console.timeEnd("FirstCalculation");

console.time("1_Memoized");
memoizedExpensiveCalculation();
console.timeEnd("1_Memoized");

console.time("2_Memoized");
memoizedExpensiveCalculation();
console.timeEnd("2_Memoized");

console.time("3_Memoized");
memoizedExpensiveCalculation();
console.timeEnd("3_Memoized");

The time logs reveals, in fact, the first time takes much more time (which we would expect) and less time afterwards.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

it's not correct


The code you shows

function memoize(result) {
  let cache = {};

  return function() {
    if (cache[result]) {
      // returns cached result / no calculation
      return cache[result];
    }
    // calculating...
    cache[result] = result;
    return cache[result];
  };
}

is basically

function memoize(result) {
  return result
}

in memoization what you cache is input/output pair and skip real function call when input match.

about 4 years ago · Juan Pablo Isaza Report

0

something like:

function get(func) {
  let cache = {};

  return function(key) {
    if (key in cache) {
      return cache[key];
    }
    cache[key] = func(key);
    return cache[key];
 };
}

function expensiveCalculation(param) {
  console.log('expensive calculation runs')
  let counter = 0;
  for (let i = 0; i < 10000; i++) {
    counter += i;
  }
  return param*2;
}
const memo = get(expensiveCalculation)
console.log('start')
console.log('first try');
console.log(memo(10));
console.log('second try');
console.log(memo(10));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!