TGViewer
JavaScript JavaScript @javascript · 31.1K subscribers
Post #2561 4.1K
CHALLENGE

class StateMachine {
constructor() {
this.state = 'idle';
this.transitions = {
idle: { start: 'running' },
running: { pause: 'paused', stop: 'stopped' },
paused: { resume: 'running', stop: 'stopped' },
stopped: { reset: 'idle' }
};
}

transition(action) {
const next = this.transitions[this.state]?.[action];
if (next) this.state = next;
return this.state;
}
}

const sm = new StateMachine();
console.log(sm.transition('start'));
console.log(sm.transition('invalid'));
console.log(sm.transition('pause'));
console.log(sm.transition('resume'));
console.log(sm.transition('stop'));
console.log(sm.transition('reset'));
  • ❤ 10
  • 👍 1
More from @javascript
  1. Oct 2, 2026😮 How Anthropic Made Claude's Apps 3x Faster in Two Weeks A grab bag of performance lesso…
  2. Oct 2, 2026Post #3532
  3. Oct 2, 2026CHALLENGE const arr = [1, 2, 3]; const log = []; const result = arr.map((x, i) => { if (i…
  4. Oct 1, 2026Post #3530
  5. Oct 1, 2026CHALLENGE class Counter { #count = 0; static #instances = 0; constructor() { Counter.#inst…
  6. Sep 30, 2026Post #3528
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →