用javascript实现typeof、Symbol

115 阅读1分钟

实现typeof

function _typeof(any) {
    let t = Object.prototype.toString.call(any).split(" ");
    t = t.substring(0, t.length - 1).toLowerCase();
    return ['regexp', 'date', 'array', 'map', 'set'].includes(t) ? 'object' : t;
}

实现Symbol

function _Symbol(n) {
    const rnd = num => Math.random() * Math.pow(2, num) | 0;
    if (!_Symbol.cache) _Symbol.cache = Object.create(null);
    let t; 
    do {t = String(n) + rnd(8)} while (_Symbol.cache[t]);
    _Symbol.cache[t] = true;
    return 'Symbol(' + t + ')';
}