debugging - deal with too many state -


my question pretty hard explain, i'll try explain briefly :

i try reproduce timer timer in website : https://cstimer.net/

the problem have : have deal many "states" , many events :

the type of event have :

chrono not started -> press "space" -> color becomes orange -> after 500ms -> chrono becomes green -> release space -> chrono start -> press space -> chrono stop

i write code that. problem code becomes complicated because of many "if".

if (!chronoisstarted , spaceispressed) { chrono.color = orange } if (lastkeydown - lastkeyup >= 500 , !chronoisstarted) { chrono.color = green } if (keyup == space , lastkeydown - lastkeyup >= 500) { chono.start(); }  ... ... 

this horrible because have have flag variable prevent chrono stop directly after start.

i'm looking way manage properly.

i heard finite machine state, don't know if it's solution.

currently, use react / redux , jquery events, can add libraries can help.

thanks you

take @ rxjs. rxjs reactive library allowing manipulate asynchronous streams. in particular example keep code declarative , keeps being cluttered global state.

for introduction, check out egghead.io course here: https://egghead.io/lessons/rxjs-what-is-rxjs

or check out introduction reactive programming: https://gist.github.com/staltz/868e7e9bc2a7b8c1f754

for example in case, take @ fiddle can make more complicated examples: http://jsfiddle.net/bryanph/5rkbxgtj/

// press space clickspace event // hold space holdspace event  var chrono = {    isstarted: false }  document.body.style.backgroundcolor = "red"  var spaceup = rx.observable.fromevent(document.body, 'keyup')     .filter(x => x.keycode === 32)  var spacedown = rx.observable.fromevent(document.body, 'keydown')     .filter(e => e.keycode === 32)   .filter(e => !e.repeat)   .partition(x => chrono.isstarted)  var chronostarted = spacedown[0]; var chronostopped = spacedown[1];  var clickspace = chronostopped.flatmap(function(e) {     return spaceup.timeout(200, rx.observable.empty()) })  var holdspace = chronostopped         .flatmap(function(e) {         return rx.observable           .return(e)           .delay(500)           .takeuntil(spaceup)           .take(1)     })  clickspace.subscribe(function(x) {   document.body.style.backgroundcolor = "orange" })  holdspace.subscribe(function(x) {     console.log('called')     document.body.style.backgroundcolor = "green" }) 

Comments