| 1 | import { IEventBus } from './interface'; |
| 2 | |
| 3 | export class EventBus implements IEventBus { |
| 4 | private eventBusCore = []; |
| 5 | |
| 6 | private areFuncEqual(a, b) { |
| 7 | return a.toString() === b.toString(); |
| 8 | } |
| 9 | |
| 10 | private isKeyValueObjInArr(arr, key, val) { |
| 11 | const filteredArr = arr.filter((entry) => { |
| 12 | return entry[key] === val; |
| 13 | }); |
| 14 | return filteredArr.length > 0; |
| 15 | } |
| 16 | |
| 17 | private removeFuncInFuncArr(arr, fn) { |
| 18 | for (let z = 0; z < arr.length; z++) { |
| 19 | if (this.areFuncEqual(arr[z], fn)) { |
| 20 | arr.splice(z, 1); |
| 21 | } |
| 22 | } |
| 23 | return arr; |
| 24 | } |
| 25 | |
| 26 | private getKeyValueObjInArr(arr, key, val) { |
| 27 | const filteredArr = arr.filter((entry) => { |
| 28 | return entry[key] === val; |
| 29 | }); |
| 30 | return filteredArr[0]; |
| 31 | } |
| 32 | |
| 33 | private addEvent(eventName, eventFunc) { |
| 34 | if (!this.isKeyValueObjInArr(this.eventBusCore, 'eventName', eventName)) { |
| 35 | this.eventBusCore.push({ eventName: eventName, eventFuncArr: [eventFunc] }); |
| 36 | } else { |
| 37 | this.eventBusCore = this.eventBusCore.map((event) => { |
| 38 | if (event.eventName === eventName) { |
| 39 | event.eventFuncArr.push(eventFunc); |
| 40 | } |
| 41 | return event; |
| 42 | }); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | public add(...rest): void { |
| 47 | const eventName = rest[0]; |
| 48 | const callbacks = rest[1]; |
| 49 | if (!eventName) { |
| 50 | return; |
| 51 | } |
| 52 | if (typeof callbacks === 'function') { |
| 53 | for (let i = 1; i < rest.length; i++) { |
| 54 | this.addEvent(eventName, rest[i]); |
| 55 | } |
| 56 | } |
| 57 | if (typeof callbacks === 'object' && callbacks.forEach) { |
| 58 | callbacks.forEach((fn) => { |
| 59 | this.addEvent(eventName, fn); |
| 60 | }); |
nothing calls this directly
no outgoing calls
no test coverage detected