百度百科: 柯里化(Currying)是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数且返回结果的新函数的技术。

示例函数

  1. // 判断传入的内容和类型是否一直
  2. const checkType = function (type, content) {
  3. return Object.prototype.toString.call(content) === `[object ${type}]`
  4. }
  5. console.log('原始版-类型是否正确 :>> ', checkType('Number', 10));

简易版: 针对指定函数柯里化

  1. // 1. 传入类型
  2. const simpleCurrying = function (type) {
  3. // 2. 传入内容
  4. return function (content) {
  5. // 3. 执行函数checkType
  6. return checkType(type, content);
  7. };
  8. };
  9. const isNumberSimple = simpleCurrying('Number')
  10. console.log('简易版-类型是否正确 :>> ', isNumberSimple(10));

通用的柯里化函数

  1. /**
  2. * 函数=>柯里化
  3. * @param {*} func 待柯里化的函数
  4. * @param {*} args 保存参数列表
  5. * @returns
  6. */
  7. function createCurry(func, args = []) {
  8. // 获取func的参数个数
  9. const funcSize = func.length
  10. // 依次拆分func为更明确的函数
  11. return function () {
  12. // 获取当前传入的参数列表
  13. const params = Array.prototype.slice.call(arguments)
  14. // 依次缓存参数列表直到满足执行func为止
  15. const _args_ = args.concat(params)
  16. if (_args_.length < funcSize) {
  17. // 递归创建执行下一步的函数
  18. return createCurry(func, _args_)
  19. }
  20. // 参数列表一致后执行func函数
  21. return func(..._args_)
  22. }
  23. }
  24. const curryingType = createCurry(checkType)
  25. const isNumber = curryingType('Number')
  26. console.log('通用版-类型是否正确 :>> ', isNumber(10));