## ES6如何用一句代码实现函数的柯里化

2020年02月18日 ⁄ 共 2690字 ⁄ 字号 评论关闭

let store = (a,b,c) => "这是你的七仔面"//函数就好像一个小卖部，一碗七仔面要三张软妹币：a,b,c (五个参数)

let curryStore = curry(store) //刚刚的小卖部被柯里化了//最佳状况curryStore(1,5,1)// 老板，刚好！不用找了，刚好七块钱。老板： "这是你的七仔面" //偶尔出现的情况let boss = curryStore(5) //老板，这五块钱你先拿着，我找找有没有一块钱。老板：……boss = boss(1) //有了老板，这一块钱你先拿着，我找找还有没有一块钱。。老板：……boss(1) //哈哈，终于找到了，给！老板："这是你的七仔面" curryStore(5)(1)(1) //等价于上诉情况

let curryPlus = curry((a,b,c) => a+b+c) //这里给到一个有三个参数的函数curryPlus(1)(2)(3) //返回 6curryPlus(1)(2,3) //返回 6curryPlus(1,2)(3) //返回 6let x = curryPlus(1)(2) //喂，怎么才两个参数？返回一个curry函数（已经带了两个参数）x(1) //返回 4x(2) //返回 5

const curry = (fn) => { return (...args) =>{ //不定参数，想给多少给多少 //给钱交货环节 }}

const curry = (fn，arr=[]) => { //arr数组用于记录已有参数 return (...args) =>{ //给钱交货环节 }}

const curry = ( fn, arr = []) => { return (...args) => { //判断参数总数是否和fn参数个数相等 if([...arr, ...args].length === fn.length){ return fn(...arr, ...args) //拓展参数，调用fn }else{ return curry(fn,[...arr, ...args]) //迭代，传入现有的所有参数 } }}

const curry = ( fn, arr = []) => { return (...args) => { return ( a => { //a是一个数组 if(a.length === fn.length) { return fn(...a) }else{ return curry(fn, a) } })([...arr, ...args]) //这里把arr和args摊开成一个数组赋值给a }}

if语句可以缩减成三元表达式，也可以省掉很多字啦：

const curry = ( fn, arr = []) => { return (...args) => { return ( a => { return a.length === fn.length ? fn(...a) : curry(fn, a) })([...arr, ...args]) }}

const curry = ( fn, arr = []) => { return (...args) => { return ( a => a.length === fn.length? fn(...a) : curry(fn, a))([...arr, ...args]) //先折叠一层 }}

const curry = ( fn, arr = []) => { return (...args) => ( a => a.length === fn.length? fn(...a) : curry(fn, a))([...arr, ...args]) //再折叠}

const curry = ( fn, arr = []) => (...args) => ( a => a.length === fn.length? fn(...a) : curry(fn, a))([...arr, ...args])//衣服给您叠好了

const curry = ( fn, arr = []) => (...args) => ( a => a.length === fn.length? fn(...a) : curry(fn, a))([...arr, ...args])let curryPlus = curry((a,b,c,d)=>a+b+c+d)curryPlus(1,2,3)(4) //返回10curryPlus(1,2)(4)(3) //返回10curryPlus(1,2)(3,4) //返回10

const curry = ( fn, arr = []) => (...args) => ( (a,b) => b.length === 0? fn(...a) : curry(fn, a))([...arr, ...args],[...args])let curryPlus = curry((...x)=>x.reduce((a,b)=>a+b))curryPlus(1) //返回一个函数curryPlus(1)(2) //返回一个函数//遇到参数个数为0的情况才执行curryPlus(1)(2)(4)() //返回7curryPlus(1,2)(4)() //返回7