Skip to content

Instantly share code, notes, and snippets.

@benzen
Last active February 17, 2016 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benzen/9ced7a3345b56d5b2af6 to your computer and use it in GitHub Desktop.
Save benzen/9ced7a3345b56d5b2af6 to your computer and use it in GitHub Desktop.
Maybe the samllest flux implementation ever
//utilitary functions
const find = (pred, coll) => {
for(const item of coll){
if(pred(item)){
return item;
}
}
return null;
};
const actionTypeIs = (actionType) => {
return (handlerDesc) => { return handlerDesc[0] === actionType; }
};
//flux container
var g = function*(initialState, handlers){
let store = initialState;
while(true){
const {actionType, payload} = yield store;
const handlerDesc = find(actionTypeIs(actionType), handlers);
if (!handlerDesc) {
throw `[ERROR] No handlers is registred for this action type ${actionType}`;
}
store = handlerDesc[1](store, payload);
}
}
//reducers
const inc = (state, payload) => { return state + 1; }
const dec = (state, payload) => { return state - 1; }
//instantiation of the genux container
var gen = g(0, [["inc", inc], ["dec", dec]]);
gen.next();
// usage of the container
console.log(gen.next({actionType:"inc"})); //{ value: 0, done: false }
console.log(gen.next({actionType:"inc"})); //{ value: 1, done: false }
console.log(gen.next({actionType:"inc"})); //{ value: 2, done: false }
console.log(gen.next({actionType:"dec"})); //{ value: 1, done: false }
console.log(gen.next({actionType:"dev"})); //thow [ERROR] No handlers is registred for this action type dev
//run with
//babe-node genux.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment