function Mediator(obj) {
  const channels = {}

  const mediator = {
    subscribe: function (channel, cb) {
      if (!channels[channel]) {
        channels[channel] = []
      }
      channels[channel].push(cb)
      return this.unsubscribe.bind(null, channel, cb)
    },

    unsubscribe: function (channel, cb) {
      let rs = channels[channel]
      let index = -1
      if (rs) {
        for (let i = 0; i < rs.length; i++) {
          if (rs[i].name === cb.name) {
            index = i
            break
          }
        }
        if (index >= 0) {
          channels[channel].splice(index, 1)
          return true
        }
      }
      return false
    },

    publish: function (channel) {
      if (!channels[channel]) {
        return false
      }
      const args = Array.prototype.slice.call(arguments, 1)
      channels[channel].forEach(subscription => {
        subscription.apply(null, args)
      })
      return this
    },
  }

  return obj ? Object.assign(obj, mediator) : mediator
}
const mediator = new Mediator()
export default mediator  
