JS 函数柯里化

80 阅读1分钟

函数柯里化

基本版

js
    <script>
        // 基本版
        const reg = /^\w{4,6}$/
        const str = 'QF001'

        console.log(reg.test(str))  //true
    </script>

封装函数

js
     // 封装函数
        function test(reg,str) {
            return reg.test(str)
        }

        console.log(test(/^\w{4,6}$/,'asdsa'))   // true
        console.log(test(/^\w{4,6}$/,'123sda'))  // true
        console.log(test(/^\w{4,6}$/,'saa'))     // false

封装柯里化函数

js
    柯里化函数,其实还是一个函数,只不过是将原本接收多个参数才能正常使用的函数
    拆分为多个函数,每个函数只接受一个参数
js
      // 封装柯里化函数
        function test(reg) {
            return function (str) {
                return reg.test(str)
            }
        }

        const res = test(/^\d{2,5}$/)
        console.log(res('sad1'))  // false
        console.log(res('123'))   // true
        console.log(res('123456'))// false
        
        
        // 案例
        function fn(a, b, c, d) {
            return a + '://' + b + ':' + c + d
        }


        function keli(callback,...args1) {
            return (...args2) => {
                args2 = [...args1,...args2]
                if(args2.length >= callback.length){
                    return callback(...args2)
                }else{
                    return keli(callback,...args2)
                }
            }
        }


        const res1 = keli(fn,'http','127.0.0.1')
        console.log(res1)  // 返回 内层函数  

        const res2 = res1('8081','/a.html')
        console.log(res2)  // http://127.0.0.1:8081/a.html