Skip to content

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

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

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

#1142

3+1官网

我也要出题

Activity

lyh-code

lyh-code commented on Mar 27, 2021

@lyh-code

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

whuigo

whuigo commented on Mar 27, 2021

@whuigo

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

rubickecho commented on Feb 9, 2022

@rubickecho
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@rubickecho@whuigo@lyh-code

        Issue actions

          [js] 第711天 实现一个函数柯里化 · Issue #3740 · haizlin/fe-interview