bredele / mood

:speak_no_evil: Give some mood to your code with a finite state machine
76 stars 1 forks source link

How can you make the 'after' state dynamic? #9

Closed foxdonut closed 4 years ago

foxdonut commented 4 years ago

Unless I'm missing something, there does not seem to be a way to make the 'after' state dynamic.

What if, when you're in state 'a' and event 'foo' occurs, the next state depends on some condition?

bredele commented 4 years ago

@foxdonut Sorry for the late reply. Working on that today!

bredele commented 4 years ago

@foxdonut I bumped the version to 2.0.0. Mood now is fully asynchronous. It accept resolution and rejection states as well as dynamic transition states. Here's a example:

mood({
  'init': [cb, 'start'],
  'start': ['condition1, () => Promise.resolve('hello'), 'pending'],
  'pending': ['condition2', () => Promise.reject('world'), 'resolved', 'rejected'],
  'rejected': [() => 'success', str => str === 'success' ? 'end' : 'init'],
  'end': [() => {
    // this is the end
   }]
})

All examples are available in the unit tests. I will do more tests and create documentation once I am sure everything is solid.

foxdonut commented 4 years ago

Nice! Thanks @bredele

bredele commented 4 years ago

@foxdonut please let me know if you think it has all the features you need. I might in the next few days add 'multiple conditions', see example:

const machine = mood({
  'init': [['condition1', 'condition2'], cb, 'ready'],
  'ready': [fn]
})
machine.trigger('condition1').then(console.log)
// => init
machine.trigger('condition2').then(console.log)
// => ready