haizlin / fe-interview

前端面试每日 3+1,以面试题来驱动学习,提倡每日学习与思考,每天进步一点!每天早上5点纯手工发布面试题(死磕自己,愉悦大家),6000+道前端面试题全面覆盖,HTML/CSS/JavaScript/Vue/React/Nodejs/TypeScript/ECMAScritpt/Webpack/Jquery/小程序/软技能……
http://www.h-camel.com
MIT License
25.47k stars 3.26k forks source link

[js] 第711天 实现一个函数柯里化 #3740

Open haizhilin2013 opened 3 years ago

haizhilin2013 commented 3 years ago

第711天 实现一个函数柯里化

1142

3+1官网

我也要出题

lyh-code commented 3 years ago

function sum(a){ return(b)=>{ return (c)=>{ return a+b+c } } } console.log(sum(1)(2)(3))

whuigo commented 3 years ago

let result=0 const curryScore = function(fn){ let score = [] return function(){ if(arguments.length === 0){ fn.apply(null,score) }else{ score = score.concat(Array.prototype.slice.call(arguments,0)) } } } const addScore = curryScore(function(){

result = Array.prototype.slice.call(arguments,0).reduce(function(prev,next){
    return prev+next
})

}) addScore(1) addScore(2) addScore() console.log(result)

function add(...args){

return args.reduce((a, b) => a + b)

}

function currying(fn){ // 返回一个函数用于接收参数 let score = [] return function inner(...args){

    //判断 如果调用函数中没有传入参数则 返回结果 否则返回自身
    if(args.length === 0){
        return fn.apply(this,score)
    }else{
        score = [...score,...args]
        return inner
    }
}

} let addCurry = currying(add) console.log(addCurry(1)(2)(3)())

rubickecho commented 2 years ago
const curry = function(fn) {
        const arity = fn.length; // 获取参数个数

        return function $curry(...args) {
            if (args.length === arity) {
                return fn.apply(this, args);
            } else {
                return function(...args2) {
                    return $curry.apply(this, args.concat(args2));
                }
            }
        }
    }

    const test = function(a, b, c) {
        return a + b + c;
    }

    const curriedTest = curry(test);
    const result = curriedTest(1)(2)(3);
    console.log('result:', result); // 6

    const result2 = curriedTest(1)(2, 3);
    console.log('result2:', result2); // 6