Skip to content

Commit

Permalink
feat(api): add matches fn, heirarchical states
Browse files Browse the repository at this point in the history
  • Loading branch information
sidiousvic committed Jul 16, 2022
1 parent 47151ae commit 203d46a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
34 changes: 31 additions & 3 deletions mod_test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
import { motor, MotorSpec } from "./mod.ts";

type Gears = "stopped" | "paused" | "playing" | "loading";
type Gears = "stopped" | "paused" | "playing" | "playing.skipping" | "loading";

type Events = "SELECT" | "LOAD" | "PLAY" | "PAUSE" | "STOP";
type Events =
| "SELECT"
| "LOAD"
| "PLAY"
| "PAUSE"
| "STOP"
| "SKIP_START"
| "SKIP_END";

const musicPlayerMotor: MotorSpec<Gears, Events> = {
gear: "stopped",
Expand All @@ -18,7 +25,10 @@ const musicPlayerMotor: MotorSpec<Gears, Events> = {
on: { PLAY: "playing", STOP: "stopped" },
},
playing: {
on: { PAUSE: "paused", STOP: "stopped" },
on: { PAUSE: "paused", STOP: "stopped", SKIP_START: "playing.skipping" },
},
"playing.skipping": {
on: { SKIP_END: "playing" },
},
},
};
Expand Down Expand Up @@ -67,3 +77,21 @@ Deno.test("Calls hooked functions to changes in gear", () => {

assertEquals(counter, 3);
});

Deno.test("Should support heirarchical state nodes", () => {
const { fire, gear, matches } = motor(musicPlayerMotor);

fire("LOAD");

assertEquals(gear(), "loading");

fire("PLAY");

assertEquals(gear(), "playing");

fire("SKIP_START");

assertEquals(matches("playing"), true);
assertEquals(matches("playing.skipping"), true);
assertEquals(matches("loading"), false);
});
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export const motor = <E extends string, G extends string>(
transmission.push(e);
},
gear: () => _gear,
matches: (gear: G) => _gear.includes(gear),
fire: (event: E) => {
if (event) {
const toGear = machine.transmission[_gear].on[event] ?? "";
Expand Down

0 comments on commit 203d46a

Please sign in to comment.