const ActionReducers = require("./action_reducer");
const registerActionReducers = require("./action_reducers");
let ar = new ActionReducers();
registerActionReducers(ar);
const reducer = ar.reducer;
const { bla } = ar.actions;
let resp = bla(1, 2);
console.log(resp);
console.log(reducer({cla: 42, cle: 13}, resp));
module.exports = actionReducers => {
actionReducers.createAction("bla", (ble, bli) => ({ble, bli}));
actionReducers.createReducer("bla", (draft, action) => draft.bla = action.ble);
actionReducers.createAction("ble", op => ({type: op == "+" ? "PLUS" : "MINUS"}));
actionReducers.createReducer("PLUS", (draft, action) => draft.result = draft.x + draft.y);
actionReducers.createReducer("MINUS", (draft, action) => draft.result = draft.x - draft.y);
}
class ActionReducers {
constructor() {
this.reducers = {}
this.actions = {}
}
createReducer(name, reducer) {
name = transformReducerName(name);
if(name in this.reducers) throw `Reducer named '${name}' already exists.`;
if(typeof reducer != 'function') throw `Reducer '${name}' is not a function.`
this.reducers[name] = reducer;
}
createAction(name, action) {
if(name in this.actions) throw `Action named '${name}' already exists.`;
if(typeof action != 'function') throw `Action '${name}' is not a function.`
this.actions[name] = wrapAction(name, action);
}
get reducer() {
return this.runReducer.bind(this)
}
runReducer(state, action) {
if(!(action.type in this.reducers)) return state;
let draft = clone(state);
this.reducers[action.type](draft, action);
return draft
}
}
function wrapAction(name, func) {
return (...data) => Object.assign({}, {type: transformReducerName(name)}, func(...data))
}
function clone(obj){
if(obj===null || typeof obj !== "object")
return obj;
if(obj instanceof Date)
return new Date(obj.getTime());
if(Array.isArray(obj))
return obj.slice(0);
let clonedObj = new obj.constructor();
for(var prop in obj){
if(obj.hasOwnProperty(prop)){
clonedObj[prop] = clone(obj[prop]);
}
}
return clonedObj;
}
function transformReducerName(name) {
return name.toUpperCase()
}
module.exports = ActionReducers