2018年8月

用 Map 结构来实现此功能,Test Case 如下:

const ee = new EventEmmiter();

ee.on('e1', function() {
  console.log('trigger e1');
});

ee.on({
  e1: function() {
    console.log('trigger e11');
  },
  e2: function() {
    console.log('trigger e2');
  }
});

ee.trigger('e2');
ee.trigger('e2');
ee.trigger('e2');
ee.trigger('e1');

setTimeout(_ => {
  ee.off('e1');
  ee.off('e2');
}, 1000);

下面是源码的实现:

const _events = {};

const has = name => _events[name] !== void 0;

const hasOwn = (obj, key) => ({}.hasOwnProperty.call(obj, key));

const eachObject = (obj, cb) => {
  for (let key in obj) {
    if (hasOwn(obj, key)) {
      cb(key, obj[key]);
    }
  }
};

class EventEmmiter {
  on(name, handler) {
    if (typeof name === 'string') {
      if (typeof handler !== 'function') {
        throw new Error('handle must is function.');
      }

      if (has(name)) {
        _events[name].push(handler);
      } else {
        _events[name] = [handler];
      }
    } else if (typeof name === 'object') {
      eachObject(name, (key, handle) => {
        if (has(key)) {
          _events[key].push(handle);
        } else {
          _events[key] = [handle];
        }
      });
    }

    return () => {
      if (typeof name === 'string') {
        this.off(name);
      } else if (typeof name === 'object') {
        eachObject(name, key => {
          this.off(key);
        });
      }
    };
  }

  trigger(name, args = [], context = this) {
    const handlers = _events[name];
    if (handlers && handlers.length > 0) {
      handlers.forEach(handle => handle.call(context, args));
    }
  }

  off(name) {
    _events[name] = null;
    delete _events[name];
  }
}

如果要实际使用的话可以将判断 Object 替换为 is-plain-object 这个类库。

找出数组中出现次数最多的元素,这个解法有 bug

var each = [].forEach;
function search(arr) {
  var counts = {};

  each.call(arr, val => {
    if (counts[val] === void 0) {
      counts[val] = 0;
    }
    counts[val]++;
  });

  var maxCount = counts[arr[0]];
  var maxNumber = 0;

  each.call(arr, val => {
    if (counts[val] > maxCount) {
      maxCount = counts[val];
    }
  });

  each.call(arr, val => {
    if (counts[val] === maxCount) {
      maxNumber = val;
    }
  });

  return maxNumber;
}

Windows 上有 xshell 工具可以做收藏,但是 Mac 配置后可能更加方便和强大,网上有很多这方面的文章,这里自己也记录一下,方便以后查阅。下面介绍 2 种方式:

  1. sshpass
  2. expect

- 阅读剩余部分 -