Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

部分柯里化函数题 #2

Open
H246802 opened this issue Dec 20, 2018 · 2 comments
Open

部分柯里化函数题 #2

H246802 opened this issue Dec 20, 2018 · 2 comments

Comments

@H246802
Copy link
Owner

H246802 commented Dec 20, 2018

柯里化(Currying),又称为部分求值,是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回一个新的函数的技术,新函数接受余下参数并返回运算结果。

@H246802
Copy link
Owner Author

H246802 commented Dec 25, 2018

请写出一个柯里化其他函数的函数 curry,这个函数能够将接受多个参数的函数,变成多个接受一个参数的函数

function curry(fn,arg){
  ???
  return ???
}
var abc = function(a, b, c) {
  return [a, b, c];
};

var curried = curry(abc);

curried(1)(2)(3);
// 输出 => [1, 2, 3]

curried(1, 2)(3);
// 输出 => [1, 2, 3]

curried(1, 2, 3);
// 输出 => [1, 2, 3]

Answer:

curry柯里化abc函数

function curry(fn,arg){
  var thisArg = arg ? arg : []
  return function(){
     // 判断总共传入参数是否达标,未达标继续柯里化过程
    if(thisArg.length + [...arguments].length < 3){
        return curry(fn,[...thisArg,...arguments])
    }else{                
	// 达到指定长度调用 abc 函数
        return fn.apply(null,[...thisArg,...arguments])
    }
  }
}
var abc = function(a, b, c) {
  return [a, b, c];
};

var curried = curry(abc);

curried(1)(2)(3);
// 输出 => [1, 2, 3]

curried(1, 2)(3);
// 输出 => [1, 2, 3]

curried(1, 2, 3);
// 输出 => [1, 2, 3]

curry函数进行适量优化,使用立即执行函数,不在内部暴露 curry

function curry(fn,arg){

  return (function rez(fn,arg){
    var thisArg = arg ? arg : []
      return function(){
       // 判断总共传入参数是否达标,未达标继续柯里化过程
        if(thisArg.length + [...arguments].length < 3){
          return rez(fn,[...thisArg,...arguments])
      }else{                
	  // 达到指定长度调用 abc 函数
        return fn.apply(null,[...thisArg,...arguments])
      }
  } 
  })(fn,arg)
  
}

@H246802
Copy link
Owner Author

H246802 commented Dec 25, 2018

实现一个sum函数, sum(1)(2)(3) 输出 6,sum(2)(2)(2)(2) 输出8,参数不限量

function sum(){
  let args = [...arguments]
  function _sum(){
    args = [...args,...arguments]
    return _sum
  }
  _sum.valueOf = function(){
    return args.reduce((a,b)=> a + b,0)
  }
  return _sum
}
console.log(sum(1,2).valueOf())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant