This is a set of tiny utilities you can use in your code or to study.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 
lcthw-utilities/js/fsm_test.mjs

56 lines
1.1 KiB

import FSM from "./fsm.mjs";
import assert from "assert";
const add_test = () => {
console.log("Additional function call on state transition passed.");
}
class TestMachine {
constructor(data) {
console.log("DATA IS", data);
this.data = data;
}
async open(state, inc) {
switch(state) {
case "START":
console.log("THIS", this);
this.data.count = this.data.count + inc;
return "OPEN";
default:
return "ERROR";
}
}
close(state, inc) {
switch(state) {
case "OPEN":
this.data.count = this.data.count + inc;
return ["CLOSED", add_test];
default:
return "ERROR";
}
}
}
let data = {count: 0};
let events = new TestMachine(data);
let fsm1 = new FSM(data, events);
fsm1.onTransition((fsm) => {
console.log("On transition: ", fsm.state);
});
await fsm1.do('open', 3);
assert(fsm1.state === "OPEN");
assert(data.count === 3);
await fsm1.do('close', 4);
assert(fsm1.state === "CLOSED");
assert(data.count === 7);
// test the errors
await fsm1.do('open');
assert(fsm1.state === "ERROR");
assert(data.count === 7); // still 2 after error