Created
August 8, 2023 17:12
-
-
Save moimikey/7d6a62ac16c6221937c28c167928cbae to your computer and use it in GitHub Desktop.
trivial heart beat state-machine simulation in js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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