[XState] Create Actor in Vanilla Javascript
function countBehavior(state, event) {
if (event.type === "INC") {
return {
...state,
count: state.count + 1
}
}
}
function createActor(behavior, initialState) {
let currentState = initialState
const listeners = new Set()
return {
send: (event) => {
currentState = behavior(currentState, event)
listeners.forEach(listener => {
listener(currentState)
})
},
subscribe: (listener) => {
listeners.add(listener)
listener(currentState)
},
getSnapshot: () => {
return currentState
}
}
}
const actor = createActor(countBehavior, {count: 12})
actor.subscribe(console.log)