30-seconds-of-code: Potential memory leak in createEventHub

Created on 12 Apr 2019  路  3Comments  路  Source: 30-seconds/30-seconds-of-code

Bug description

https://github.com/30-seconds/30-seconds-of-code#createeventhub-

on creates an array, off never removes it

Steps to reproduce

Run this code

const createEventHub = () => ({
  hub: Object.create(null),
  emit(event, data) {
    (this.hub[event] || []).forEach(handler => handler(data));
  },
  on(event, handler) {
    if (!this.hub[event]) this.hub[event] = [];
    this.hub[event].push(handler);
  },
  off(event, handler) {
    const i = (this.hub[event] || []).findIndex(h => h === handler);
    if (i > -1) this.hub[event].splice(i, 1);
  }
});

const ee = createEventHub();
let evolvingEventName = 0;
setInterval(() => {
    const eventName = String(evolvingEventName);
    ee.on(eventName, Number);
    ee.off(eventName, Number);
    evolvingEventName++;
}, 1);

setInterval(() => {
    console.log(`Number of arrays keeps growing ${Object.keys(ee.hub).length}`);
}, 1000);

Expected behavior

Expected to see the number 0

Example where it is solved

https://github.com/GrosSacASac/event-e3/blob/master/EventEmitter3.mjs#L81

Most helpful comment

This would be a great PR!

All 3 comments

This would be a great PR!

I apologize for the messy history. Everything should be in order now. It's my first time contributing here, I'll be more careful next time.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for any follow-up tasks.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

emelendez picture emelendez  路  4Comments

skatcat31 picture skatcat31  路  5Comments

ecwyne picture ecwyne  路  4Comments

henrycjchen picture henrycjchen  路  4Comments

larrybotha picture larrybotha  路  3Comments