Skip to content

Instantly share code, notes, and snippets.

@voodooattack
Created September 18, 2018 22:17
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 voodooattack/167e56f26b84a732761b57bace2582aa to your computer and use it in GitHub Desktop.
Save voodooattack/167e56f26b84a732761b57bace2582aa to your computer and use it in GitHub Desktop.
voodooattack@voodooattack:~/devel/when-ts$ tsc && node dist/lib/primeMachine.js
[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ]
voodooattack@voodooattack:~/devel/when-ts$ 
interface PrimeState extends MachineState {
counter: number;
current: number;
primes: number[];
}
class PrimeMachine extends StateMachine<PrimeState> {
constructor() {
super({ counter: 2, current: 3, primes: [2] });
}
@when(state => state.counter < state.current)
incrementCounterOncePerTick({ counter }: PrimeState) {
return { counter: counter + 1 };
}
@when(state => state.counter < state.current && state.current % state.counter === 0)
resetNotPrime({ counter, primes, current }: PrimeState) {
return { counter: 2, current: current + 1 };
}
@when(state => state.counter >= state.current)
capturePrime({ counter, primes, current }: PrimeState) {
return { counter: 2, current: current + 1, primes: [...primes, current] };
}
@when(state => state.primes.length >= 10)
exitMachine() {
this.exit();
}
}
const primeMachine = new PrimeMachine();
const result = primeMachine.run();
console.log(result!.primes);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment