Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Last active May 6, 2019 17:46
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 cowboyd/6d1496b3eb5997fe8a47a0c8090a0de8 to your computer and use it in GitHub Desktop.
Save cowboyd/6d1496b3eb5997fe8a47a0c8090a0de8 to your computer and use it in GitHub Desktop.
A primitive
import { call, variable, wait } from '@microstates/effects';
function* countToFive() {
let count = variable(1);
this.call(count, function*() { // the count variable is now the context of all operations
this.when(() => count.get() <= 5, function*() { // guard sees value of `count`
console.log(`count is ${count.get()}`);
yield wait(1000)
yield count.update(c => c + 1)
});
});
}
let main = call(countToFive);
// the effects can be closed cleanly at any time.
process.stdin.on('keypress', e => {
if (e.isCtrl && e.char === 'c') {
main.close();
}
})
import { call, state, wait } from '@microstates/effects';
// we can build on this reactive primitive effect to use
// a microstate instead. The `state` function creates an effect
// variable that is based on microstates. However, it's just a "power up"
// on the underlying mechanism.
function* countToFive() {
let count = state(Number, 1);
this.call(count, function*() { // the count variable is now the context of all operations
this.when(() => count.state <= 5, function*() { // guard sees value of `count`
console.log(`count is ${count.state}`);
yield wait(1000)
yield count.increment();
});
});
}
let main = call(countToFive);
process.stdin.on('keypress', e => {
if (e.isCtrl && e.char === 'c') {
main.close();
}
})
import { call, state, wait } from '@microstates/effects';
// finally, you can pass in a variable to your generator function.
function* countTo(count) {
this.when(() => count.state <= 5, function*() { // guard sees value of `count`
console.log(`count is ${count.state}`);
yield wait(1000)
yield count.increment();
});
}
let main = call(countTo, state(Number, 1));
process.stdin.on('keypress', e => {
if (e.isCtrl && e.char === 'c') {
main.close();
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment