Skip to content

Instantly share code, notes, and snippets.

@moimikey
Created August 8, 2023 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moimikey/7d6a62ac16c6221937c28c167928cbae to your computer and use it in GitHub Desktop.
Save moimikey/7d6a62ac16c6221937c28c167928cbae to your computer and use it in GitHub Desktop.
trivial heart beat state-machine simulation in js
class Heart {
constructor() {
this.states = {
REST: 'Resting',
CONTRACTION: 'Contracting',
RELAXATION: 'Relaxing'
};
this.transitions = {
[this.states.REST]: [this.states.CONTRACTION, 'Ventricles contract', 'Valves open'],
[this.states.CONTRACTION]: [this.states.RELAXATION],
[this.states.RELAXATION]: [this.states.REST, 'Ventricles relax', 'Valves close']
};
this.currentState = this.states.REST;
this.internalState = 0;
}
simulateHeartbeat() {
console.log(`Heart is ${this.currentState}`);
const actions = this.transitions[this.currentState];
for (const action of actions) {
if (typeof action === 'string') {
console.log(action);
} else if (action === 'Ventricles contract') {
this.internalState |= 1; // set first bit
} else if (action === 'Ventricles relax') {
this.internalState &= ~1; // clear first bit
} else if (action === 'Valves open') {
this.internalState |= 2; // set second bit
} else if (action === 'Valves close') {
this.internalState &= ~2; // clear second bit
}
}
this.currentState = actions[0];
}
}
const heart = new Heart();
// simulate heart pumping for a few cycles
for (let i = 0; i < 10; i++) {
heart.simulateHeartbeat();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment