All files / src/utils/eventBus EventBus.ts

97.43% Statements 38/39
90% Branches 9/10
100% Functions 8/8
97.29% Lines 36/37

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                          71x   71x 6x 6x 2x 2x 3x         71x 8x 8x 8x 8x 8x 9x 9x 9x 8x 8x 8x     9x                 67x 8x 8x 8x 8x 21x 21x 6x   15x 6x 6x   9x   8x     67x 210x     67x
 
 
interface ChangeEvent {
  path: string;
  payload: unknown;
}
 
export type ChangeEventCallback = (event: ChangeEvent) => void;
 
export type UnregisterCallback = () => void;
 
export class EventBus {
 
  private readonly listenersMap = new Map<string, ChangeEventCallback[]>();
 
  public on = (path: string, callback: ChangeEventCallback): UnregisterCallback => {
    this.listenersMap.set(path, [...(this.listenersMap.get(path) || []), callback]);
    return () => {
      const listeners = this.listenersMap.get(path);
      Eif (listeners) {
        this.listenersMap.set(path, listeners.filter((cb) => cb !== callback));
      }
    };
  };
 
  public emit = (path: string, payload: unknown): void => {
    console.log("Emitting event", path, payload);
    try {
      const parts = path.split("/");
      let subPath = "";
      parts.forEach((part) => {
        subPath += part;
        const listeners = this.listenersMap.get(subPath);
        if (listeners) {
          listeners.forEach((cb) => {
            console.log("Calling callback", cb, path, payload);
            cb({ path, payload });
          });
        }
        subPath += '/';
      });
    } catch (e) {
      console.error("Failed to emit event", e);
    }
  };
 
}
 
export const resolvePath = (path: string, pathExpression: string): string => {
  const pathParts = path.split("/");
  const expressionParts = pathExpression.split("/");
  const resolvedPaths = [...pathParts];
  for (let i = 0; i < expressionParts.length; i++) {
    const expressionPart = expressionParts[i];
    if (expressionPart === ".") {
      continue;
    }
    if (expressionPart === "..") {
      resolvedPaths.splice(resolvedPaths.length - 1, 1);
      continue;
    }
    resolvedPaths.push(expressionPart);
  }
  return resolvedPaths.join("/");
};
 
export const buildPath = (parentPath: string, key: string): string => {
  return `${parentPath}/${key}`;
};
 
export const EVENT_BUS = new EventBus();