Skip to content

[js] 第57天 写一个方法,使得sum(x)(y)和sum(x,y)返回的结果相同 #238

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

第57天 写一个方法,使得sum(x)(y)和sum(x,y)返回的结果相同

Activity

AnsonZnl

AnsonZnl commented on Jun 12, 2019

@AnsonZnl
Contributor
  • 写一个方法,使得sum(x)(y)和sum(x,y)返回的结果相同
var sum= function(x){
    if(arguments[1]){
        return x + arguments[1];
    }else{
        return function (y){
            return x + y
        }
    }
}
console.log(sum(1)(2))//3
console.log(sum(1,2))//3
  • 群里的提议 增加点难度 使得sum(x)(y)(z)(...)(a)和sum(x,y,z,... a)返回的结果相同
function sum(x){
    if(arguments[1]){
        var arr = Array.prototype.slice.apply(arguments);
            x = arr.reduce((a, c)=> a+ c)
        return x;
    }else{
        function add(b) { 
            x = x + b; 
            return add;
        }
        add.toString = function() { 
            return x;
        }
        return add; 
    }
}
var res1 = sum(1)(2)(3)(4)(5)(6);
var res2 = sum(1,2,3,4,5,6);
console.log(res1)//21
console.log(res2)//21

JavaScript 高阶函数浅析 获取的灵感

thisisandy

thisisandy commented on Jun 12, 2019

@thisisandy
function sum(...args) {
  function curriedSum(...rest) {
    args.push(...rest);
    return curriedSum;
  }
  curriedSum.toString = () => args.reduce((prev, curr) => curr + prev);

  curriedSum.toNumber = () => args.reduce((prev, curr) => curr + prev);
  return curriedSum;
}
thisisandy

thisisandy commented on Jun 12, 2019

@thisisandy

类似于python元编程,修改toString 和toNumber 方法,使其既可以当做数字也可以当做函数调用

SCLeoX

SCLeoX commented on Jun 13, 2019

@SCLeoX

function sum(x){
if(arguments[1]){
var arr = Array.prototype.slice.apply(arguments);
x = arr.reduce((a, c)=> a+ c)
return x;
}else{
function add(b) {
x = x + b;
return add;
}
add.toString = function() {
return x;
}
return add;
}
}
var res1 = sum(1)(2)(3)(4)(5)(6);
var res2 = sum(1,2,3,4,5,6);
console.log(res1)//21
console.log(res2)//21

虽然我一时半会没想出什么解决方案但是你这个无限 curry 的不太行啊,除了显然的 typeof 结果不一样以外,还有这种,所以得到的值并不能放心用:

sum(1,2,3).toExponential(3);
// "6.000e+0"

sum(1)(2)(3).toExponential(3);
// VM1727:1 Uncaught TypeError: sum(...)(...)(...).toExponential is not a function
//    at <anonymous>:1:14
Gxmg

Gxmg commented on Jun 14, 2019

@Gxmg

作者 怎么也不最后给个答案呀

forever-z-133

forever-z-133 commented on Jun 14, 2019

@forever-z-133
Function.prototype.currying = function() {
  var fn = this, _args = [];
  var _temp = function() {
    _args = _args.concat([].slice.call(arguments));
    return _temp;
  }
  _temp.toString = _temp.valueOf =function(){
    return fn.apply(fn, _args);
  }
  return _temp;
}
function adder() {
  return [].slice.call(arguments).reduce(function(a,b){return a+b});
}
var sum = adder.currying();
console.log(sum(2,4)(3));  // ƒ 9
haizhilin2013

haizhilin2013 commented on Jun 14, 2019

@haizhilin2013
CollaboratorAuthor

@Gxmg 没有最后的答案

hn-failte

hn-failte commented on Jun 25, 2019

@hn-failte

此题考函数式编程:
const sum = (x, y) => (typeof y === "undefined") ? (y)=> x+y : x+y

console.log(sum(1,3));

console.log(sum(1)(3));

yuqingc

yuqingc commented on Jul 1, 2019

@yuqingc

Lodash _.curry()
可以看人家实现

haizhilin2013

haizhilin2013 commented on Jul 1, 2019

@haizhilin2013
CollaboratorAuthor

@yuqingc 那你自己来实现一个呢?

chenyouf1996

chenyouf1996 commented on Jul 26, 2019

@chenyouf1996
//函数柯理化
function sum1(x, y, z) {
  return x + y + z
}
function sum2() {
  var args = arguments
  return function () {
    var arr = []
    arr.push(...args, ...arguments)
    return arr.reduce((total, item) => total += item, 0)
  }
}
console.log(sum1(6, 9, 14)) //29
console.log(sum2(6)(9, 14)) //29
Vi-jay

Vi-jay commented on Jul 31, 2019

@Vi-jay
function currying(fn) {
  let args = [];
  return function closureFn() {
    args = args.concat(Array.from(arguments));
    if (args.length < fn.length) return closureFn;
    const res = fn.apply(this, args);
    args = [];
    return res;
  }
}

const sum = currying((a, b) => a + b);
console.log(sum(1, 2) === sum(1)(2)); // true
lizheng1991

lizheng1991 commented on Aug 23, 2019

@lizheng1991

综合一下大家的写法,再自由发挥一下~话说怎么让代码高亮啊???

function sumfn(){
  var result=0;
  function fn(...arg){
    result = result + arg.reduce((a,b)=>a+b,0);
    return fn;
  }
  fn.toString=function(){
    var re=result;
    result=0;
    return re;
  }
  return fn;
}

var sum=sumfn();
sum(1,2,3);
sum(1)(2)(3);
sum(1)(2)(3,4,5);
YiChongXie

YiChongXie commented on Sep 29, 2019

@YiChongXie

function add(){
var args = [...arguments]
var fn = function (){
args.push(...arguments)
return fn
}
fn.toString = function(){
return args.reduce((x,y) => x + y)
}
return fn
}

geng130127

geng130127 commented on Nov 20, 2019

@geng130127

function sum(a,b){
return b?a+b:function(c){
return a+c;
}
}

rni-l

rni-l commented on Jan 19, 2020

@rni-l
function curry(...args) {
  if (args.length > 1) return args2.reduce((acc, cur) => acc + cur, 0)
  let val = 0
  function add(...args2) {
    val = args2.reduce((acc, cur) => acc + cur, val)
    return add
  }
  add.toString = function() { return val }
  val = args[0]
  return add
}

// curry(1,6)(2,5)(3,4)(7,8,9) -> 45
// curry(1) -> 1
276378532

276378532 commented on Feb 24, 2020

@276378532
 function Curry(fn, length) {
            var length = length || fn.length;
            return function (...arg) {
                if (arg.length < length) {
                    return Curry(fn.bind(this, ...arg), length - arg.length); 
                } else {
                    return fn(...arg)
                }
            }
        }
函数式编程 柯里化
Alex-Li2018

Alex-Li2018 commented on Aug 12, 2020

@Alex-Li2018
function sum(x,y) {
    return x + y;
}
sum(2,3)

const sum = x => y => x + y
function sum (x) {
     return function(y) {
        return x + y
    }
}
sum(2)(3)
laboonly

laboonly commented on Sep 10, 2020

@laboonly

function add() {
  // 第一次执行时,定义一个数组专门用来存储所有的参数
  var _args = [].slice.call(arguments);

  // 在内部声明一个函数,利用闭包的特性保存_args并收集所有的参数值
  var adder = function () {
      var _adder = function() {
          // [].push.apply(_args, [].slice.call(arguments));
          _args.push(...arguments);
          return _adder;
      };

      // 利用隐式转换的特性,当最后执行时隐式转换,并计算最终的值返回
      _adder.toString = function () {
          return _args.reduce(function (a, b) {
              return a + b;
          });
      }

      return _adder;
  }
  // return adder.apply(null, _args);
  return adder(..._args);
}


smile-2008

smile-2008 commented on Dec 7, 2020

@smile-2008
  • 写一个方法,使得sum(x)(y)和sum(x,y)返回的结果相同
var sum= function(x){
    if(arguments[1]){
        return x + arguments[1];
    }else{
        return function (y){
            return x + y
        }
    }
}
console.log(sum(1)(2))//3
console.log(sum(1,2))//3
  • 群里的提议 增加点难度 使得sum(x)(y)(z)(...)(a)和sum(x,y,z,... a)返回的结果相同
function sum(x){
    if(arguments[1]){
        var arr = Array.prototype.slice.apply(arguments);
            x = arr.reduce((a, c)=> a+ c)
        return x;
    }else{
        function add(b) { 
            x = x + b; 
            return add;
        }
        add.toString = function() { 
            return x;
        }
        return add; 
    }
}
var res1 = sum(1)(2)(3)(4)(5)(6);
var res2 = sum(1,2,3,4,5,6);
console.log(res1)//21
console.log(res2)//21

JavaScript 高阶函数浅析 获取的灵感

Huauauaa

Huauauaa commented on May 7, 2021

@Huauauaa
export const sum = (...x) => {
  let result = x.reduce((a, b) => a + b);
  const add = (...y) => {
    if (y.length === 0) {
      return result;
    }
    result += y.reduce((a, b) => a + b);
    return add;
  };

  return add;
};

console.log(sum(1, 2, 3, 4)());  // 10
console.log(sum(1)(2)(3)(4)()); // 10
console.log(sum(1, 2)(3)(4)()); // 10
console.log(sum(1)(2, 3, 4)()); // 10
xiaoqiangz

xiaoqiangz commented on Jun 9, 2022

@xiaoqiangz

柯里化函数
function sum() {
let args = [...arguments]
let fn = function() {
let fn_args = [...arguments]
return sum.apply(null, args.concat(fn_args))
}
fn.toString = function() {
return args.reduce((a, b) => a + b)
}
return fn
}
console.log(sum(1,2,3)+'')

dragon-sing

dragon-sing commented on Oct 31, 2022

@dragon-sing
const sum = (a , b) => {
  if (b) {
    return a + b;
  } else {
    return (another) => {
      return a + another;
    }
  }
}
panpanxuebing

panpanxuebing commented on Dec 13, 2024

@panpanxuebing
function sum (x, y) {
  if (y) {
    return x * y
  } else {
    return function (y) {
      return x * y
    }
  }
}
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

        @smile-2008@haizhilin2013@thisisandy@laboonly@SCLeoX

        Issue actions

          [js] 第57天 写一个方法,使得sum(x)(y)和sum(x,y)返回的结果相同 · Issue #238 · haizlin/fe-interview