-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringCalculator.ts
More file actions
32 lines (24 loc) · 1.02 KB
/
stringCalculator.ts
File metadata and controls
32 lines (24 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { NegativeNumberError } from "./util";
/*
* Input: a string of delimiter separated numbers
* Output: an integer, sum of the numbers
*/
export function add(numbers: string): number {
let result = 0;
if(numbers === "") return result;
let delimiter: RegExp = /,|\n/;
let delimiterMatchRegexExp: RegExpMatchArray | null = numbers.match(/^\/\/(.+)\n/);
if (delimiterMatchRegexExp) {
delimiter = new RegExp(delimiterMatchRegexExp[1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
numbers = numbers.slice(delimiterMatchRegexExp[0].length);
}
const numArray = numbers.split(delimiter).map(num => parseInt(num, 10));
let negatives: number[] = numArray.filter(num => num < 0);
if (negatives.length) {
throw new NegativeNumberError(negatives);
}
result = numArray.reduce((sum, num) => sum + num, 0);
return !Number.isNaN(result) ? result : 0;
}
const inputString = "1\n3,4" // Enter your string result
console.log(add(inputString)) //Logs the result on terminal