函数柯里化

把接收多个参数的函数转换成只接收一个参数的函数,并返回一个的函数,这个过程叫柯里化 (做到最大程度上的复用)

  • 参数复用
  • 延迟计算
  • 动态创建

例一:获取URL

// 普通函数
function getUrl(protocol, host, path) {
    return `${protocol}://${host}/${path}`
}
const baiduIndex = getUrl('https','www.baidu.com','index') // https://www.baidu.com/index
const taobaoIndex = getUrl('https','www.taobao.com','index') // https://www.taobao.com/index

const baiduUser = getUrl('https','www.baidu.com','user') // https://www.baidu.com/user
const taobaoUser = getUrl('https','www.taobao.com','user') // https://www.taobao.com/user

// 柯里化
function getUrl(protocol) {
    return (host) {
        return (path) {
            return `${protocol}://${host}/${path}`
        }
    }
}

const domain = getUrl('https')

const baidu = domain('www.baidu.com')
baidu('index') // https://www.baidu.com/index
baidu('user') // https://www.baidu.com/user

const taobao = domain('www.taobao.com')
taobao('index') // https://www.taobao.com/index
taobao('user') // https://www.taobao.com/user

例二:正则校验

// 普通函数
function check(regexp, str) {
    return regexp.text(str)
}
check(/^1[3456789]\d{9}$/, '18888482270') // true
check(/^1[3456789]\d{9}$/, '12345678900') // false

check(/^[+]{0,1}(\d+)$/, 100) // true
check(/^[+]{0,1}(\d+)$/, 'abc') // false

// 柯里化
function check(regexp) {
    return (str) {
        return regexp.text(str)
    }
}
const isPhone = check(/^1[3456789]\d{9}$/)
isPhone('18888482270') // true
isPhone('12345678900') // false

const isInteger = check(/^[+]{0,1}(\d+)$/)
isInteger(100) // true
isInteger('abc') // false

例三:动态添加事件函数

如果要兼容现代浏览器和IE浏览器的添加事件方法

// 通常会这么写(每次添加的时候都得判断一次)
const addEvent = function (elem, type, fn, cature) {
    if (window.addEventListener) {
        elem.addEventListener(type, (e) => fn.call(elem, e), capture)
    } else if (window.attachEvent) {
        elem.attachEvent('on' + type, (e) => fn.call(elem, e)
    }
}

// 柯里化
const addEvent = (function () {
    if (window.addEventListener) {
        return (elem, type, fn, capture) => {
            elem.addEventListener(type, (e) => fn.call(elem, e), capture)
        }
    } else {
        return (elem, type, fn, capture) => {
            elem.attachEvent('on' + type, (e) => fn.call(elem, e)
        }
    }
})()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值