All files event-emitter.js

100% Statements 25/25
92.31% Branches 12/13
100% Functions 11/11
100% Lines 24/24

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        5x 5x 5x 5x           9x       18x 16x 13x 3x     3x 2x   1x     2x           1x 1x         6x 1x   5x 5x 5x     2x 4x   2x 2x            
import { isEqual } from './utils';
 
class Observer {
  constructor(props, next, error, unsubscribe) {
    this.props = props;
    this.next = next;
    this.error = error;
    this.unsubscribe = unsubscribe;
  }
}
 
export default class EventEmitter {
  constructor() {
    this.observers = [];
  }
 
  next(prevState, state) {
    this.observers.forEach(observer => {
      if (!observer.props.length) {
        observer.next(state);
      } else if (
        observer.props &&
        observer.props.reduce((final, prop) => {
          if (!isEqual(state[prop], prevState[prop])) {
            return [...final, prop]
          }
          return final;
        }, []).length)
      {
        observer.next(state);
      }
    });
  }
 
  error(error) {
    this.observers.forEach(observer => {
      observer.error(error);
    });
  }
 
  subscribe(next, props = [], onError) {
    if (typeof next !== 'function') {
      throw TypeError(`"next" should be a function`);
    }
    const obs = new Observer(props, next, onError, this._unsubscribe);
    this.observers.push(obs);
    return { unsubscribe: () => this._unsubscribe(obs) };
  }
  _unsubscribe(thisObserver) {
    const index = this.observers.findIndex(
      observer => observer === thisObserver
    );
    Eif (index > -1) {
      this.observers = [
        ...this.observers.slice(0, index),
        ...this.observers.slice(index + 1),
      ];
    }
  }
}