DAY 30
1

# 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
``````

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

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

### Javascript

#### Init

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

#### Sample Testing

``````  Test.expect(add(1) == 1);
``````

# Thinking

• Ruby
• JavaScript

## Solution

### Ruby

``````  # Solution 1
n
end

class Fixnum
def call(m)
self + m
end
end

# Solution 2
def call(m)
return self + m
end
return n
end
``````

### Javascript

``````  // Solution 1
var fn = function(x) {
};

fn.valueOf = function() {
return n;
};

return fn;
}

// Solution2
const f = x => add(n + x)
f.valueOf = () => n
return f;
}
``````

### 1 則留言

0

iT邦新手 4 級 ‧ 2020-10-15 11:58:02

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