Please enable Javascript to view the contents

学习函数柯里化

 ·  ☕ 1 分钟

从直观上理解柯里化,就是原本需要一次传 n 个参数才可以执行一个函数,
柯里化后我可以每次只传一个单独的参数来运行一个函数

例子 1:
把特定的函数柯里化

1
2
3
// 把add(1, 2, 3) 变成curriedAdd(1)(2)(3),这就是函数柯里化

const curriedAdd = (a) => (b) => (c) => add(a, b, c)

例子 2:
做一个柯里化其他函数的函数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
addTwo = (a, b) => a + b
addThree = (a, b, c) => a + b + c
addFour = (a, b, c, d) => a + b + c + d

const currify = (fn, params = []) => {
  return (arg) => {
    const newParams = params.concat(arg)
    if (newParams.length === fn.length) {
      return fn(...newParams)
    } else {
      return currify(fn, newParams)
    }
  }
}

console.log(currify(addTwo)(1)(2)) //3
console.log(currify(addThree)(1)(2)(3)) //6
console.log(currify(addFour)(1)(2)(3)(4)) //10

例子 3:
做一个柯里化其他函数的函数(参数个数可以不限制为 1)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
addFour = (a, b, c, d) => a + b + c + d

const currify = (fn, params = []) => {
  return (...args) => {
    const newParams = params.concat(...args)
    if (newParams.length === fn.length) {
      return fn(...newParams)
    } else {
      return currify(fn, newParams)
    }
  }
}

console.log(currify(addFour)(1, 2, 3, 4)) //10
console.log(currify(addFour)(1, 2, 3)(4)) //10
console.log(currify(addFour)(1, 2)(3, 4)) //10
console.log(currify(addFour)(1)(2, 3)(4)) //10
分享

Llane00
作者
Llane00
Web Developer