All files ChainedReducer.ts

93.44% Statements 57/61
78.26% Branches 18/23
100% Functions 23/23
92.98% Lines 53/57

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173                                                        5x     4x 4x         4x 4x 3x         1x                 23x 23x 23x       48x 23x 23x 253x 253x 253x     23x   48x                 3x 2x     2x   1x     1x   3x       2x     2x   2x       1x 1x   1x             2x 2x 2x       19x     22x   19x                       2x       25x 42x     42x     42x 13x   30x         66x 66x 33x   66x 66x 41x   66x       24x 22x 24x        
import { produce } from 'immer';
import {
  AC,
  Flatten,
  ExtractPayload,
  Reducer,
  ActionLike,
  ActionType,
} from './types';
import { toArray, getACType } from './utils';
 
export type OnHandler<S, T extends AC> = (
  state: S,
  payload: ExtractPayload<ReturnType<T>>,
  action: Flatten<ReturnType<T> & { type: string }>
) => void;
 
export type ReplaceHandler<S, T extends AC> = (
  state: S,
  payload: ExtractPayload<ReturnType<T>>,
  action: Flatten<ReturnType<T> & { type: string }>
) => S;
 
export type AttachFn<S> = {
  <T extends keyof S>(prop: T, fn: Reducer<S[T]>): ChainedReducer<S>;
  (fn: Reducer<S>): ChainedReducer<S>;
};
 
const createNestedReducer = <S, P extends keyof S>(
  prop: P,
  reducer: Reducer<S[P]>
): Reducer<S> => (state, action) => {
  Iif (typeof state === 'undefined') {
    throw new Error(
      'tried to create createNestedReducer with undefined parent state'
    );
  }
  const subState = reducer(state[prop], action);
  if (state[prop] !== subState) {
    return {
      ...state,
      [prop]: subState,
    };
  }
  return state;
};
 
export class ChainedReducer<S> {
  private reducerMap: Map<symbol, Map<string, Array<Reducer<S>>>>;
  private defaultReducers: Array<Reducer<S>>;
  private reducer: ChainedReducer<S> & Reducer<S> | null;
 
  constructor(private initial: S) {
    this.reducerMap = new Map();
    this.defaultReducers = [];
    this.reducer = null;
  }
 
  asReducer() {
    if (!this.reducer) {
      const reducer: any = this.getReducer();
      Object.getOwnPropertyNames(ChainedReducer.prototype).forEach(key => {
        const prop = (this as any)[key];
        Eif (typeof prop === 'function') {
          reducer[key] = prop.bind(this);
        }
      });
      this.reducer = reducer;
    }
    return this.reducer!;
  }
 
  attach<T extends keyof S>(fn: Reducer<S>): ChainedReducer<S> & Reducer<S>;
  attach<T extends keyof S>(
    prop: T,
    fn: Reducer<S[T]>
  ): ChainedReducer<S> & Reducer<S>;
  attach<T extends keyof S>(prop: T | Reducer<S>, fn?: Reducer<S[T]>) {
    if (typeof prop === 'string') {
      Iif (typeof fn !== 'function') {
        throw new Error('fn must be a function');
      }
      this.defaultReducers.push(createNestedReducer(prop, fn));
    } else {
      Iif (typeof prop !== 'function') {
        throw new Error('fn must be a function');
      }
      this.defaultReducers.push(prop);
    }
    return this.asReducer();
  }
 
  replace<T extends AC>(actionCreator: T, fn: ReplaceHandler<S, T>) {
    this.transform(
      actionCreator,
      (state, action: any) =>
        produce(state, draft => fn(draft as S, action.payload, action))!
    );
    return this.asReducer();
  }
 
  mergePayload(actionCreators: AC) {
    this.transform(actionCreators, (state, action: any) =>
      Object.assign({}, state, action.payload)
    );
    return this.asReducer();
  }
 
  nested<T extends keyof S>(
    prop: T,
    fn: (reducer: ChainedReducer<S[T]>) => ChainedReducer<S[T]>
  ) {
    const nested = fn(new ChainedReducer(this.initial[prop]));
    this.defaultReducers.push(createNestedReducer(prop, nested.getReducer()));
    return this.asReducer();
  }
 
  on<T extends AC>(actionCreator: T, fn: OnHandler<S, T>) {
    this.transform(
      actionCreator,
      (state, action: any) =>
        produce(state, draft => fn(draft as S, action.payload, action))!
    );
    return this.asReducer();
  }
 
  onMany<T extends AC, T2 extends AC>(
    actionCreator: [T, T2],
    fn: OnHandler<S, T | T2>
  ): Reducer<S> & this;
  onMany<T extends AC, T2 extends AC, T3 extends AC>(
    actionCreator: [T, T2, T3],
    fn: OnHandler<S, T | T2 | T3>
  ): Reducer<S> & this;
  onMany(actionCreator: any, fn: OnHandler<S, AC>) {
    return this.on(actionCreator, fn);
  }
 
  private getReducer() {
    return (state: S = this.initial, action: ActionLike) => {
      Iif (!action.type) {
        throw new Error('action.type must be defined');
      }
      const reducers = this.getReducers(action.type).concat(
        this.defaultReducers
      );
      if (!reducers.length) {
        return state;
      }
      return reducers.reduce((prev, fn) => fn(prev, action), state);
    };
  }
 
  private getReducers(actionType: ActionType) {
    const [symbol, type] = actionType!;
    if (!this.reducerMap.has(symbol)) {
      this.reducerMap.set(symbol, new Map());
    }
    const map = this.reducerMap.get(symbol)!;
    if (!map.has(type)) {
      map.set(type, []);
    }
    return map.get(type)!;
  }
 
  private transform(actionCreators: AC | AC[], reducerFn: Reducer<S>) {
    const actionTypes = toArray(actionCreators).map(ac => getACType(ac));
    actionTypes.forEach(action => {
      this.getReducers(action).push(reducerFn);
    });
  }
}