实现 JavaScript 常用工具函数

By bobo 2021-12-21 18:28:51 文章分类:JavaScript

防抖

function debounce(fn, delay) {
    let timer = null

    return function () {
        let context = this
        let args = arguments

        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(function () {
            fn.apply(context, args)
        }, delay)
    }
}

节流

function throttle(fn, interval) {
    let last = 0

    return function () {
        let args = arguments
        let context = this
        let now = Date.now()

        if (now - last > interval) {
            last = now
            fn.apply(context, args)
        }
    }
}

深拷贝

function deepClone(source) {
    if (typeof source !== 'object' || source == null) {
        return source
    }

    let target = source instanceof Array ? [] : {}
    for (let k in source) {
        if (Object.prototype.hasOwnProperty.call(source, k)) {
            if (typeof source[k] === 'object') {
                target[k] = deepClone(source[k])
            } else {
                target[k] = source[k]
            }
        }
    }

    return target
}

柯里化

原理:用闭包把参数保存起来,当参数的数量足够执行函数了,就开始执行函数

function curry(fn, args) {
    var length = fn.length
    args = args || []

    return function () {
        const _args = args.concat([].slice.call(arguments))
        if (_args.length < length) {
            return curry.call(this, fn, _args)
        }

        return fn.apply(this, _args)
    }
}

extend

function extend() {
    var args = Array.prototype.slice.call(arguments)
    var length = args.length
    if (args.length === 0) return false

    for (var j = 0; j < args.length; j++) {
        if (typeof args[j] !== 'object' || args[j] === null) {
            throw new TypeError(args[j] + ' Object prototype may only be an Object')
        }
    }

    var i = 0
    var target = args[i++]
    for (; i < length; i++) {
        var source = args[i]
        for (let key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)) {
                target[key] = source[key]
            }
        }
    }

    return target
}