Last active
February 17, 2016 03:49
-
-
Save benzen/9ced7a3345b56d5b2af6 to your computer and use it in GitHub Desktop.
Maybe the samllest flux implementation ever
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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