
export default () => {
  let listeners = []

  function getIndex(name) {
    for (let i = 0; i < listeners.length; i += 1) {
      const fn = listeners[i]
      if (fn.name === name) {
        return i
      }
    }

    return -1
  }
  
  function remove(name) {
    listeners = listeners.filter((f) => f.name !== name)
  }

  function append(fun, name) {
    if (!name) {
      name = Math.random().toString(36).substring(2)
    }

    const pos = getIndex(name)
    if (pos === -1) {
      listeners.push({ name, fun })
    }
    return () => remove(name)
  }

  function getListeners() {
    return listeners.map((listener) => listener.fun)
  }

  return {
    getListeners,
    append,
  }
}
