dphilipson / typescript-fsa-reducers

Fluent syntax for defining typesafe reducers on top of typescript-fsa.
MIT License
220 stars 16 forks source link

why not use map? #31

Closed DiamondYuan closed 5 years ago

DiamondYuan commented 5 years ago

why not use map

import { ActionCreator, AnyAction, isType } from 'typescript-fsa';

export type Handler<P> = (
  payload: P,
  sender: chrome.runtime.MessageSender,
  sendResponse: (response: any) => void
) => any;

interface Case<P> {
  actionCreator: ActionCreator<P>;
  handler: Handler<P>;
}

interface ListenerCombiner {
  case<P>(
    actionCreator: ActionCreator<P>,
    handler: Handler<P>
  ): ListenerCombiner;
}

export class MessageListenerCombiner implements ListenerCombiner {
  private cases: Map<string, Case<any>>;

  constructor() {
    this.cases = new Map();
  }

  case = <P>(actionCreator: ActionCreator<P>, handler: Handler<P>) => {
    this.cases.set(actionCreator.type, { actionCreator, handler });
    return this;
  };

  handle = (action: AnyAction, sender: any, sendResponse: any) => {
    const actionCase = this.cases.get(action.type);
    if (actionCase) {
      const { actionCreator, handler } = actionCase;
      if (isType(action, actionCreator)) {
        handler(action.payload, sender, sendResponse);
      }
    }
  };
}
DiamondYuan commented 5 years ago

https://github.com/dphilipson/typescript-fsa-reducers/blob/39038b4019b759e95f732d3d1edfc9bed5c22689/src/index.ts#L180

i think map.get is master than for loop

dphilipson commented 5 years ago

Very good catch, you're quite right. I'm not going to use a Map for the sake of unfortunate people in environments that don't have it (e.g. IE 10), but doing this with an object to look up makes good sense. Fixed in https://github.com/dphilipson/typescript-fsa-reducers/commit/7a681624db665e6371d7f7f30d4653ba255b7d27.