Skip to content

Compile Library away to imperative code #34

@royalicing

Description

@royalicing

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 }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions