-
Notifications
You must be signed in to change notification settings - Fork 219
Expand file tree
/
Copy pathCalculator.js
More file actions
44 lines (35 loc) · 1.08 KB
/
Calculator.js
File metadata and controls
44 lines (35 loc) · 1.08 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
33
34
35
36
37
38
39
40
41
42
43
44
class Calculator {
parseInput(input){
let numbersPart = input;
const customSeperator = this.getCustomSeperator(input);
if(customSeperator) {
numbersPart = input.split(`\\n`)[1];
}
return this.splitNumbers(numbersPart, customSeperator);
}
getCustomSeperator(input){
if(!input.startsWith("//")) return null;
const match = input.match(/^\/\/(.*?)\\n/);
return match ? match[1] : null;
}
splitNumbers(numbersPart, customSeperator = null) {
let delimiters = ",:";
if(customSeperator) {
delimiters += customSeperator;
}
const regex = new RegExp(`[${delimiters}]`);
return numbersPart.split(regex);
}
validateNumbers(numbers) {
numbers.forEach((value) => {
const num = Number(value);
if(isNaN(num) || num < 0) {
throw new Error("[ERROR]");
}
});
}
sum(numbers) {
return numbers.reduce((sum, value) => sum + Number(value), 0);
}
}
export default Calculator;