Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- interface IReducerState{
- someNumber: number;
- };
- const rootReducer = {
- getInitialState: function():IReducerState{
- return {
- someNumber: 42,
- };
- }
- };
- const addReducer = {
- addOne: function(prevState:IReducerState):IReducerState{
- prevState.someNumber += 1;
- return prevState;
- }
- };
- const Reducer = debug(
- extend(rootReducer,addReducer)
- );
- export default Reducer;
- /////////////////////////////////////////////////
- /// Helpers
- /////////////////////////////////////////////////
- // Takes two typed variables and returns a combined type
- function extend<T,U>(first: T,second:U):T & U{
- let result = {};
- for(let id in first){
- (result as any)[id] = (first as any)[id];
- }
- for(let id in second){
- if(!result.hasOwnProperty(id)){
- (result as any)[id] = (second as any)[id];
- }
- }
- return result as T & U;
- }
- // Takes a reducer object and returns a copy that logs actions
- function debug<T>(reducer:T):T{
- Object.keys(reducer).forEach(function(key){
- if(key == 'getInitialState'){
- const initialFunction = reducer['getInitialState'];
- reducer[key] = function(){
- const result = initialFunction();
- console.log('State initialized',result);
- return result;
- }
- }
- else{
- const originalFunc = reducer[key];
- reducer[key] = function(){
- const funcResult = originalFunc.apply(this,arguments);
- return function(prevState){
- const actualResult = funcResult(prevState);
- console.log('State changed ('+key+')',actualResult);
- }
- }
- }
- });
- return reducer;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement