Created
May 23, 2022 01:14
-
-
Save Grubba27/490a7db34b864a43bf06b406d8ddb8fd to your computer and use it in GitHub Desktop.
Normal TS calculator made with pattern mathing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type Operations = 'sum' | 'sub' | 'mul' | 'div'; | |
| type RecursiveReturn = [number, (args: Array<number>, next?: Operations) => RecursiveReturn] | |
| const calculator = | |
| (operation: Operations, prev?: number) => | |
| (args: Array<number>, next?: Operations): RecursiveReturn => { | |
| const nums = prev === undefined ? [...args] : [...args, prev]; | |
| const partial = nums | |
| .reduce((prev: number, curr: number) => ({ | |
| ['sum']: prev + curr, | |
| ['sub']: prev - curr, | |
| ['mul']: prev * curr, | |
| ['div']: prev / curr, | |
| }[operation]), 0); | |
| if (next) { | |
| return [partial, calculator(next, partial)] | |
| } | |
| return [partial, calculator(operation, partial)] | |
| } | |
| const sum = calculator('sum'); | |
| const [res] = sum([1,2]); | |
| console.log(res); // 3 | |
| const mul = calculator('mul'); | |
| const [res2, mul2] = mul([1,2], "mul"); | |
| console.log(res2); // 2 | |
| const [res3, calc2] = mul2([2]); | |
| console.log(res3); // 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment