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

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

Open
haizhilin2013 opened this issue Jun 11, 2019 · 23 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

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

@AnsonZnl
Copy link
Contributor

AnsonZnl commented Jun 12, 2019

  • 写一个方法,使得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
Copy link

thisisandy commented Jun 12, 2019

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
Copy link

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

@SCLeoX
Copy link

SCLeoX commented Jun 13, 2019

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
Copy link

Gxmg commented Jun 14, 2019

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

@forever-z-133
Copy link

forever-z-133 commented Jun 14, 2019

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
Copy link
Collaborator Author

@Gxmg 没有最后的答案

@haizhilin2013 haizhilin2013 added the js JavaScript label Jun 18, 2019
@hn-failte
Copy link

hn-failte commented Jun 25, 2019

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

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

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

@yuqingc
Copy link

yuqingc commented Jul 1, 2019

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

@haizhilin2013
Copy link
Collaborator Author

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

@chenyouf1996
Copy link

//函数柯理化
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
Copy link

Vi-jay commented Jul 31, 2019

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
Copy link

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

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
Copy link

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
Copy link

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

@rni-l
Copy link

rni-l commented Jan 19, 2020

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
Copy link

 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
Copy link

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
Copy link


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);
}


@MrZ2019
Copy link

MrZ2019 commented Dec 7, 2020

  • 写一个方法,使得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
Copy link

Huauauaa commented May 7, 2021

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
Copy link

柯里化函数
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
Copy link

const sum = (a , b) => {
  if (b) {
    return a + b;
  } else {
    return (another) => {
      return a + another;
    }
  }
}

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

No branches or pull requests