Console.log is giving a weird result when using closure, recursion, and memoization? (simple factorial func)

22 views Asked by At
const memoFactorial = () => {
  let cache = { 1: 1 }
  return function factorial(n) {
    console.log(cache)
    if (n in cache) {
      console.log('Fetching from cache:', n)
      return cache[n]
    } else {
      console.log(`Calculating result for ${n}:`)
      let result = n * factorial(n - 1)
      cache[n] = result
      return result
    }
  }
}

const closedMemoFactorial = memoFactorial()

console.log(closedMemoFactorial(5))

The result from the console gives:

Object {1: 1, 2: 2, 3: 6, 4: 24, 5: 120}
Calculating result for 5:
Object {1: 1, 2: 2, 3: 6, 4: 24, 5: 120}
Calculating result for 4:
Object {1: 1, 2: 2, 3: 6, 4: 24, 5: 120}
Calculating result for 3:
Object {1: 1, 2: 2, 3: 6, 4: 24, 5: 120}
Calculating result for 2:
Object {1: 1, 2: 2, 3: 6, 4: 24, 5: 120}
Fetching from cache: 1
120

Following the code sequentially, I was expecting the cache to update once as the function calls return back up the recursive stack but instead it looks like the cache has all the values at every single step of the recursion, which is really unexpected. Anyone know why this is happening? Does javascript push off the console.log until the inner scope is completely handled or something similar?

I tried placing the console.log in different parts of the inner function (factorial) and still got the same result.

Update: this looks like a bug with the Replit console

0

There are 0 answers