SOURCE

function myall(iterator) {
    return new Promise((res, rej) => {
        let len = 0;
        let count = 0;
        let reslist = []
        for (let p of iterator) {
            let resindex = len++;
            Promise.resolve(p).then((res) => {
                reslist[resindex] = res;
                if (++count === len) res(reslist)
            }).catch(rej)
        }
        if (len === 0) res(reslist)
    })
}

function deepcopy(target, hash = new WeakMap()) {
    const type = Object.prototype.toString.call(target).slice(8, -1)
    // [object object]
    let res;
    if (type === 'Object') res = {}
    else if (type === 'Array') res = []
    else return target
    if (hash.has(target)) return hash.get(target)
    hash.set(res)
    for (let key in target) {
        res[key] = deepcopy(target[key], hash)
    }
    return res
}

function asyncpool(poollimit, urls, request) {
    let ret = []
    let executing = []
    let i = 0
    const enqueue = () => {
        if (i === urls.length) return Promise.resolve()
        const url = urls[i++]
        const p = Promise.resolve(request(url))
        ret.push(p)
        executing.push(p)
        p.then(() => executing.splice(executing.indexOf(p), 1))
        let r = Promise.resolve();
        if (executing.length >= poollimit) r = Promise.race(executing);
        return r.then(() => enqueue())
    }
    return enqueue().then(() => Promise.all(ret))
}

function sort(nums) {
    if (!nums || nums.length <= 1) return nums;
    let left = [], right = [];
    let middle = nums.splice(Math.floor(nums.length / 2), 1)[0]
    nums.forEach(item => {
        if (item < middle) left.push(item)
        else right.push(item)
    })
    return sort(left).concat(middle, sort(right))
}

// 二分查找
function seach(nums, target) {
    let left = 0; right = nums.length - 1;
    while (left <= right) {
        let middle = Math.floor(left + (right - left) / 2)
        if (nums[middle] === target) return middle
        let isSmall = nums[middle] < target
        left = isSmall ? middle + 1 : left
        right = isSmall ? right : middle - 1
    }
    return -1
}


class Event {
    _handlers = {}

    on(type, handler) {
        this._handlers[type] = this._handlers[type] || []
        this._handlers[type].push(handler)
    }
    emit(type, ...args) {
        if (!this._handlers[type]) throw Error('type invalid')
        this._handlers[type].forEach(handler => handler(...args))
    }
    off(type, handler) {
        if (!this._handlers[type]) throw Error('type invalid')
        if (!handler) delete this._handlers[type]
        else {
            let idx = this._handlers[type].indexOf(handler)
            if(idx === -1) throw Error('handler invalid')
            this._handlers[type].splice(idx, 1)
            if (this._handlers[type].length === 0) delete this._handlers[type]

        }
    }
}
console 命令行工具 X clear

                    
>
console