All files create-object.ts

100% Statements 18/18
100% Branches 4/4
100% Functions 5/5
100% Lines 16/16

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 551x 1x 1x           1x 8x 8x         8x 1x       8x       2x   2x   1x         1x                     1x   15x   8x            
import { BehaviorSubject } from 'rxjs';
import { AnyAction, Constants, Dispatch, getType } from './utils';
import {
  CreateStateRxOpts,
  CreateStateRxApi,
  createStateRx
} from './create-staterx';
 
const createActions = <T>({
  constant,
  dispatch
}: {
  constant: Constants;
  dispatch: Dispatch;
}) => {
  return {
    merge: (data: Partial<T>) => dispatch({ type: constant.MERGE, data })
  };
};
 
const createReducer = <T>({ constant }: { constant: Constants }) => (
  state: any,
  action: AnyAction
): T => {
  const type = getType(action);
 
  switch (type) {
    case constant.MERGE:
      return {
        ...state,
        ...action.data
      };
    default:
      return state;
  }
};
 
export interface CreateObjectOpts<T, E>
  extends CreateStateRxOpts<E, StateRxObject<T>, T> {}
 
export interface StateRxObject<T> extends CreateStateRxApi<T> {
  merge: (data: Partial<T>) => { type: string; data: T };
}
 
export const createObject = <T extends {}, E>(
  initialState: T,
  options: CreateObjectOpts<T, E> = {}
) =>
  createStateRx(initialState, options, {
    state$: new BehaviorSubject<T>(initialState),
    constants: ['MERGE'],
    createActions,
    createReducer
  });