All files / src/Graph event.ts

100% Statements 25/25
100% Branches 8/8
100% Functions 8/8
100% Lines 25/25

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                            8x             8x 7x   8x               4x 1x   3x 3x 2x                 14x 7x   7x 6x         9x 9x 9x       1x 1x 1x       2x 2x 2x       1x 1x 1x      
import Graph from '.';
 
type GraphEventType = 'nodeAdd' | 'nodeRemove' | 'edgeAdd' | 'edgeRemove';
 
export class GraphWithEvent<
  NodeIDType = string,
  NodeType = Record<string, any>,
  EdgeType = Record<string, any>,
  GraphType = string,
> extends Graph<NodeIDType, NodeType, EdgeType, GraphType> {
  /**
   * @description a pool of event listeners.
   * @description.zh-CN 事件监听器池。
   */
  private eventPool: Record<string, Function[]> = {};
 
  /**
   * @description Add an event listener.
   * @description.zh-CN 添加事件监听器。
   */
  public appendEvent(type: GraphEventType, callback: Function) {
    if (!this.eventPool[type]) {
      this.eventPool[type] = [];
    }
    this.eventPool[type].push(callback);
  }
 
  /**
   * @description remove an event listener.
   * @description.zh-CN 移除事件监听器。
   */
  public removeEvent(type: GraphEventType, callback: Function) {
    if (!this.eventPool[type]) {
      return;
    }
    const index = this.eventPool[type].indexOf(callback);
    if (index > -1) {
      this.eventPool[type].splice(index, 1);
    }
  }
 
  /**
   * @description trigger an event.
   * @description.zh-CN 触发事件。
   */
  public emitEvent(type: GraphEventType, ...args: any[]) {
    if (!this.eventPool[type]) {
      return;
    }
    this.eventPool[type].forEach((callback) => {
      callback(...args);
    });
  }
 
  setNode(node: NodeIDType, value?: NodeType) {
    super.setNode(node, value);
    this.emitEvent('nodeAdd', node, value);
    return this;
  }
 
  removeNode(node: NodeIDType) {
    super.removeNode(node);
    this.emitEvent('nodeRemove', node);
    return this;
  }
 
  setEdge(v_: NodeIDType, w_: NodeIDType, value?: any, name?: string | undefined) {
    super.setEdge(v_, w_, value, name);
    this.emitEvent('edgeAdd', v_, w_, value, name);
    return this;
  }
 
  removeEdge(v_: NodeIDType, w_: NodeIDType, name?: any) {
    super.removeEdge(v_, w_, name);
    this.emitEvent('edgeRemove', v_, w_, name);
    return this;
  }
}