add kata
This commit is contained in:
25
5kyu/a-chain-adding-function/description.md
Normal file
25
5kyu/a-chain-adding-function/description.md
Normal file
@@ -0,0 +1,25 @@
|
||||
We want to create a function that will add numbers together when called in succession.
|
||||
```ts
|
||||
add(1)(2); // == 3
|
||||
```
|
||||
We also want to be able to continue to add numbers to our chain.
|
||||
```ts
|
||||
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 be equal to the number passed in.
|
||||
```ts
|
||||
add(1); // == 1
|
||||
```
|
||||
We should be able to store the returned values and reuse them.
|
||||
```ts
|
||||
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.
|
||||
8
5kyu/a-chain-adding-function/solution.ts
Normal file
8
5kyu/a-chain-adding-function/solution.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
|
||||
export default function add(x: number): any {
|
||||
const sum = (y: number): any => add(x + y);
|
||||
// set .valueOf to return the current sum when the object is coerced to a primitive
|
||||
// for example, when it is compared to a number
|
||||
sum.valueOf = () => x;
|
||||
return sum;
|
||||
}
|
||||
14
5kyu/a-chain-adding-function/tests.ts
Normal file
14
5kyu/a-chain-adding-function/tests.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import add from './solution';
|
||||
import {assert} from "chai";
|
||||
|
||||
describe('solution', () => {
|
||||
it('should work when called once', () => {
|
||||
assert(add(1) == 1);
|
||||
});
|
||||
it('should work when called twice', () => {
|
||||
assert(add(1)(2) == 3);
|
||||
});
|
||||
it('should work when called 5 times', () => {
|
||||
assert(add(1)(2)(3)(4)(5) == 15);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user