vaco
v3.0.1
Published
some useful tools for programming
Downloads
24
Maintainers
Readme
Staty
Staty is a state machine library that takes an object with boolean values as the first parameter and handlers as the second parameter. Handlers can have keys representing states or combinations of states separated by ",". You can place "!" at the beginning of a key to indicate that it must be false for the handler to apply.
Each handler function must return a function, even if it's empty, which will be called for cleanup purposes. The staty
function returns another function that takes a new state (or a partial state) to change the previous state and checks the handlers. Handlers that satisfy the new state will be called, and previously applied handlers won't be called twice.
If a handler doesn't satisfy the new state, it will be deleted, and the returned function will be called for cleanup.
Here's an example:
const states = { foo: true, bar: true }
const retFn = jest.fn()
const handlers = {
"foo, !bar": jest.fn(() => retFn),
"!foo, !bar": jest.fn(),
}
const changeState = staty(states, handlers)
changeState({ bar: false })
changeState({ foo: false, bar: true })
expect(handlers["foo, !bar"]).toHaveBeenCalledTimes(1)
expect(retFn).toHaveBeenCalledTimes(1)
expect(handlers["!foo, !bar"]).toHaveBeenCalledTimes(0)