iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 30
1
自我挑戰組

見習村-30 Day CodeWars Challenge系列 第 30

見習村30 - A Chain adding function

  • 分享至 

  • xImage
  •  

30 - A Chain adding function

Don't say so much, just coding...

Instruction

We want to create a function that will add numbers together when called in succession.

  add(1)(2);
  // returns 3

We also want to be able to continue to add numbers to our chain.

  add(1)(2)(3); // 6
  add(1)(2)(3)(4); // 10
  add(1)(2)(3)(4)(5); // 15

and so on.

A single call should return the number passed in.

  add(1); // 1

We should be able to store the returned values and reuse them.

  var addTwo = add(2);
  addTwo; // 2
  addTwo + 5; // 7
  addTwo(3); // 5
  addTwo(3)(5); // 10

We can assume any number being passed in will be valid whole number.

Ruby

Init

  def add(n)
    # ...
  end

Sample Testing

  Test.expect(add(1) == 1);
  Test.expect(add(1).(2) == 3);
  Test.expect(add(1).(2).(3) == 6);

Javascript

Init

  function add(n){
    // Let the currying begin!
  }

Sample Testing

  Test.expect(add(1) == 1);
  Test.expect(add(1)(2) == 3);
  Test.expect(add(1)(2)(3) == 6);

Thinking

https://ithelp.ithome.com.tw/upload/images/20201015/20120826uwpX2JABrn.jpg
圖片來源:Unsplash Martin Garrido

Hint & Reference

Solution

Ruby

  # Solution 1
  def add(n)
    n
  end
  
  class Fixnum
    def call(m)
      self + m
    end
  end
  
  # Solution 2
  def add(n)
    def call(m)
      return self + m
    end
    return n
  end

Javascript

  // Solution 1
  function add(n){
    var fn = function(x) {
      return add(n + x);
    };
    
    fn.valueOf = function() {
      return n;
    };
    
    return fn;
  }
  
  // Solution2
  function add(n) {
    const f = x => add(n + x)
    f.valueOf = () => n
    return f;
  }

上一篇
見習村29 - Sum of Intervals
系列文
見習村-30 Day CodeWars Challenge30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
小菜
iT邦新手 3 級 ‧ 2020-10-15 11:58:02

恭喜完賽~~

Chester iT邦新手 4 級 ‧ 2020-10-15 17:35:49 檢舉

你上班各種留言誒 太神了吧大大

我要留言

立即登入留言