Description

JavaScript arrays are powerful but passive — they don’t tell you when something changes.


In this challenge, you’ll make arrays “reactive” by extending the Array so they can dispatch custom events whenever elements are added or removed.


This mimics the kind of reactivity used by frameworks like Vue or MobX, where state changes automatically trigger updates elsewhere in the app.

Your task is to build small helper methods that:

  • Allow registering event listeners for "add" and "remove".
  • Trigger these listeners when elements are pushed or popped using special methods.
  • Remove listeners when they are no longer needed.

Implementation Details

Implement the following methods on Array so that it work natively.

  • addListener(eventName: string, callback: Function): void
    Registers a callback to be called whenever the specified event occurs.
    Example: "add" → triggered when items are added.
  • pushWithEvent(eventName: string, values: any[]): void
    Pushes new items into the array and triggers the "add" listener (if present).
  • you should also Pass (eventName, values, this (context) ) to the registered event while dispatching the event
  • popWithEvent(eventName: string): void
    Removes the last item from the array and triggers the "remove" listener (if present).
  • removeListener(eventName: string): void
    Unregisters the listener for the given event name.

Each array should maintain its own listeners, so changes to one array don’t affect others.

Example

Input

const arr = [];

arr.addListener("add", (eventName, items, array) => {
console.log("items were added:", items);
});

arr.addListener("remove", (eventName, item, array) => {
console.log("item removed:", item);
});

arr.pushWithEvent("add", [4, 5]);
arr.popWithEvent("remove");

Expected Output

items were added: [4, 5]
item removed: 5

Constraints

  • Do not use external libraries.
  • Each array instance must handle its own listeners (no shared/global state).
  • Only "add" and "remove" events are used in testing.

Hints

Hint 1

Think about array prototype and see how you can add methods on it

Hint 2

Use Object.defineProperty to attach a hidden listeners object to each array instance.

Hint 3

Use spread syntax (this.push(...values)) to add multiple elements at once.