JSFiddle - React, Tailwind, and code Playground
by evgkch
JavaScript
class FSM {
constructor(map, cache){
this.rules = {};
map(this._define);
}
_define(rule){
const [action, transition] = Object.entries(rule);
if (action in this.rules)
this.rules[action].push(transition);
else
this.rules[action] = [transition];
}
dispatch(action){
if (this.rules[action.type])
{
this.rules[action.type].find()
}
}
}
const map = define => {
define({ take: (i) =>
[
'standing',
'pending',
cache => cache.cell(i).state == 1,
(err, cache) => {
if (!err)
cache.cell(i).switch();
}
]
});
define({ move: () => ['pending', 'moving'] });
define({ put: (i) =>
[
'moving',
'standing',
cache => cache.cell(i).state == 0,
(err, cache) => {
if (!err)
cache.cell(i).switch();
}
]
});
};
class Cell {
constructor(initialState){
this.state = initialState;
}
switch(){
this.state = ~this.state;
}
}
const cache = [1, 0, 1, 0];
cache.cell = function(i){
return {
switch(){
if (typeof(cache[i]) == 'number')
cache[i] = ~cache[i];
},
state: cache[i]
};
}
const tile = new FSM(map, cache);