Advertisement
Guest User

Untitled

a guest
Jan 4th, 2018
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. interface IReducerState{
  2.     someNumber: number;
  3. };
  4.  
  5. const rootReducer = {
  6.     getInitialState: function():IReducerState{
  7.         return {
  8.             someNumber: 42,
  9.         };
  10.     }
  11. };
  12.  
  13. const addReducer = {
  14.     addOne: function(prevState:IReducerState):IReducerState{
  15.         prevState.someNumber += 1;
  16.         return prevState;
  17.     }
  18. };
  19.  
  20. const Reducer = debug(
  21.     extend(rootReducer,addReducer)
  22. );
  23.  
  24. export default Reducer;
  25.  
  26. /////////////////////////////////////////////////
  27. ///                  Helpers
  28. /////////////////////////////////////////////////
  29.  
  30. // Takes two typed variables and returns a combined type
  31. function extend<T,U>(first: T,second:U):T & U{
  32.     let result = {};
  33.  
  34.     for(let id in first){
  35.         (result as any)[id] = (first as any)[id];
  36.     }
  37.  
  38.     for(let id in second){
  39.         if(!result.hasOwnProperty(id)){
  40.             (result as any)[id] = (second as any)[id];
  41.         }
  42.     }
  43.  
  44.     return result as T & U;
  45. }
  46.  
  47.  
  48. // Takes a reducer object and returns a copy that logs actions
  49. function debug<T>(reducer:T):T{
  50.     Object.keys(reducer).forEach(function(key){
  51.         if(key == 'getInitialState'){
  52.             const initialFunction = reducer['getInitialState'];
  53.  
  54.             reducer[key] = function(){
  55.                 const result = initialFunction();
  56.                 console.log('State initialized',result);
  57.                 return result;
  58.             }
  59.         }
  60.         else{
  61.             const originalFunc = reducer[key];
  62.  
  63.             reducer[key] = function(){
  64.                 const funcResult = originalFunc.apply(this,arguments);
  65.  
  66.                 return function(prevState){
  67.                     const actualResult = funcResult(prevState);
  68.  
  69.                     console.log('State changed ('+key+')',actualResult);
  70.                 }
  71.             }
  72.         }
  73.     });
  74.  
  75.     return reducer;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement