高阶函数-柯里化、防抖、节流

什么是高阶函数

数学计算机科学中,高阶函数是至少满足下列一个条件的函数

  • 接受一个或多个函数作为输入
  • 输出一个函数

高阶函数的应用

柯里化

简短的来说就是分步处理

function currying(fn) {
    return (...argu) => {
        let result = fn(argu)

        function _fn(...argu) {
            argu = argu.concat(result)
            result = fn(argu)
            _fn.toString = () => result

            return _fn
        }

        _fn()

        return _fn
    }
}

function _add(argu) {
    return argu.reduce((result, currentItem) => result + +currentItem, 0)
}
function _store(argu) {
    return argu.reduce((result, currentItem) => result * +currentItem, 1)
}

const add = currying(_add)
const store = currying(_store)

console.log(add(1)(2)(3))
console.log(add(5))
console.log(store(1, 2)(3)(4))

防抖

当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,
如果设定的时间到来之前,又一次触发了事件,就重新开始延时

function debounce(cb, time) {
    let timeId = null

    return () => {
        if (timeId) clearTimeout(timeId)

        timeId = setTimeout(cb, time)
    }
}

节流

当持续触发事件时,保证一定时间段内只调用一次事件处理函数

function throttle(cb, time) {
    let preDate = new Date().getTime()

    return () => {
        const nowDate = new Date().getTime()
        if (nowDate - preDate >= time) {
            cb()
            preDate = nowDate
        }
    }
}

【笔记不易,如对您有帮助,请点赞,谢谢】

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容