Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
[RC Diary] Lazy evaluation first steps (-77)

[RC Diary] Lazy evaluation first steps (-77)

Lazy evaluation in JavaScript

So following on yesterday's white paper reading group I am trying to code lazy evaluation in JavaScript, I want to understand how it could be useful to glue modules together.

I would like to do so without any extra constructs like yield or generators.

Sadly both JavaScript REPLS in Spacemacs SPC-m-e-e do not seem to work, so I can't evaluate expressions as I'm used in ClojureScript, I will probably have to look into this.

First attempt

function thunk() {
  let args = arguments
  return function() { return args; }
}

function sumGenerator(prev) {
  let next = prev + 1
  return [prev, thunk(sumGenerator(next))]
}

sumGenerator(0)[0]

which gives RangeError: Maximum call stack size exceedeed, because sumGenerator(next) is getting evaluated before the surrounding call to thunk.

I am giving it another try after having read this article on MDN; I wrote the evergreen Fibonacci number generator, using plain old JavaScript syntax.

const fibonacciGenerator = () => {
  let f1 = 0, f2 = 1

  const next = (reset) => {
    if (reset) {
      f1 = 0, f2 = 1
    }
    const value = f1
    f1 = f2;
    f2 = value + f1;

    return {
      next: next,
      value: value
    }
  }

  return {
    next: next,
    value: 0
  }
}

Which works as the example on MDN, without using the language features.

Project lamp

Worked again through chapter 1 and 2, introducing some small changes. Took a lot of time, I have to go carefully through every single step and see if it makes sense for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment