From ddb9925e18ca37fbe1ba49fc15307ba7e9da7af6 Mon Sep 17 00:00:00 2001 From: Loosetooth Date: Sat, 1 Feb 2025 22:56:58 +0100 Subject: [PATCH] add kata --- 5kyu/a-chain-adding-function/description.md | 25 +++++++++++++++++++++ 5kyu/a-chain-adding-function/solution.ts | 8 +++++++ 5kyu/a-chain-adding-function/tests.ts | 14 ++++++++++++ 3 files changed, 47 insertions(+) create mode 100644 5kyu/a-chain-adding-function/description.md create mode 100644 5kyu/a-chain-adding-function/solution.ts create mode 100644 5kyu/a-chain-adding-function/tests.ts diff --git a/5kyu/a-chain-adding-function/description.md b/5kyu/a-chain-adding-function/description.md new file mode 100644 index 0000000..e22ed9a --- /dev/null +++ b/5kyu/a-chain-adding-function/description.md @@ -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. \ No newline at end of file diff --git a/5kyu/a-chain-adding-function/solution.ts b/5kyu/a-chain-adding-function/solution.ts new file mode 100644 index 0000000..9ddc007 --- /dev/null +++ b/5kyu/a-chain-adding-function/solution.ts @@ -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; +} \ No newline at end of file diff --git a/5kyu/a-chain-adding-function/tests.ts b/5kyu/a-chain-adding-function/tests.ts new file mode 100644 index 0000000..aca55ce --- /dev/null +++ b/5kyu/a-chain-adding-function/tests.ts @@ -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); + }); +}); \ No newline at end of file