SOURCE

// 深拷贝
function deepClone(obj) {
    // 基本类型直接返回
    if (typeof obj !== 'object') return obj
    // 判断是数组还是对象,定义临时变量
    let temp = Array.isArray(obj) ? [] : {}
    // 循环对象的key,遍历对象的值,判断如果为引用类型,继续拷贝,基础类型赋值给新对象
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            // 浅拷贝 忽略内置对象
            //  temp[key] =obj[key] 
            temp[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key]
        }
    }
    // 返回已拷贝值的新对象
    return temp
}

// 类型判断
function typeOf(obj) {
    return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}

console.log(typeOf(new Set())) // set

// 数组去重

const arr = [1, 1, 3, 5, 5, 7]

const uniqueArr = arr => [...new Set(arr)]

function unique(arr) {
    return arr.filter((item, index, array) => array.indexOf(item) === index)
}

console.log(uniqueArr(arr))
console.log(unique(arr))

// 数组扁平化

const list = [1, [2, 3, [7, 8, [9, 10]]], 4]

console.log(list.flat(Infinity))

const flatArr = arr => {
    let result = []
    arr.forEach(item => {
        if (!Array.isArray(item)) {
            result.push(item)
        } else {
            result = result.concat(flatArr(item))
        }
    })
    return result
}

console.log(flatArr(list))

// 解析URL参数对象
function parseParam(url) {
    const paramsStr = /.+\?(.+)$/.exec(url)[1]; // 将 ? 后面的字符串取出来
    const paramArr = paramsStr.split('&')
    let paramsObj = {}
    paramArr.forEach(param=>{
        if(/=/.test(param)){
            let [key,value] = param.split('=')
            value = decodeURIComponent(value)
            value = /\d+$/.test(value)? parseFloat(value):value
            if(paramsObj.hasOwnProperty(key)){
                paramsObj[key]= [].concat(paramsObj[key],value)
            }else{
                paramsObj[key]= value
            }
        }else{
            paramsObj[param] = true
        }
    })
    return paramsObj
}

const url = 'www.baidu.com?15156265&xxxxx&zzzzz&user=zhangsan&age=15'
console.log(parseParam(url))

// 防抖

function debounce(fn,wait,immediate){
    const timer = null
    const result = null
    const debounced = function(){
        // 接收参数
        const args = arguments
        // 绑定this
        const context = this
        //立即执行
        if(immediate){
           const callNow = !timer
           setTimeout(()=>{
               timer = null
           })
           if(callNow){
            result= fn.apply(context,args)
           } 
        }else{
           timer= setTimeout(()=>{
               fn.apply(context,args)
           })

        }
    }

    debounced.cancel= function(){
       if(timer)  clearTimeout(timer)
        timer =null
    }

    return debounced
}

console 命令行工具 X clear

                    
>
console