Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compile Library away to imperative code #34

Open
RoyalIcing opened this issue Feb 22, 2022 · 0 comments
Open

Compile Library away to imperative code #34

RoyalIcing opened this issue Feb 22, 2022 · 0 comments

Comments

@RoyalIcing
Copy link
Contributor

RoyalIcing commented Feb 22, 2022

Before:

import { start } from "yieldmachine";

function TrafficLights() {
  function* Red() {
    yield on("timer", Green);
  }
  function* Green() {
    yield on("timer", Yellow);
  }
  function* Yellow() {
    yield on("timer", Red);
  }

  return Red;
}

const m = start(TrafficLights);
m.current; // { state: "Red", count: 0 }
m.next("timer");
m.current; // { state: "Green", count: 1 }
m.next("timer");
m.current; // { state: "Yellow", count: 2 }

After compiles to:

function* startTrafficLights() {
  let count = 0;
  let state = "Red";

  return {
    get current() {
      return Object.freeze({ count, state });
    }
    next(event) {
      if (event === "timer") {
        count++;
        if (state === "Red") {
          state = "Green";
        } else if (state === "Green") {
          state = "Yellow";
        } else if (state === "Yellow") {
          state = "Red";
        }
      }
      return { value: this.current, done: false };
    },
  };
}

const m = startTrafficLights();
m.current; // { state: "Red", count: 0 }
m.next("timer");
m.current; // { state: "Green", count: 1 }
m.next("timer");
m.current; // { state: "Yellow", count: 2 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant