-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringCalculator.js
More file actions
42 lines (37 loc) · 1.22 KB
/
StringCalculator.js
File metadata and controls
42 lines (37 loc) · 1.22 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
function StringCalculator() {}
StringCalculator.add = function add(instruction) {
const numbers = getNumbersString(instruction)
.split(getSplitterRegex(instruction))
.map(i => Number(i));
handleNegativeNumbers(numbers);
return numbers.filter(i => i < 1001).reduce((prev, curr) => prev + curr, 0);
};
function getNumbersString(instruction) {
const numberStringMatch = RegExp('//(.*)\n(.*)').exec(instruction);
return numberStringMatch !== null ? numberStringMatch[2] : instruction;
}
function getSplitterRegex(instruction) {
let splitterRegex = RegExp('[,\n]');
const splitterMatch = RegExp('//(.*)\n(.*)').exec(instruction);
if (splitterMatch !== null) {
const multiLengthDelimMatch = RegExp('\\[(.*)\\]').exec(splitterMatch[1]);
splitterRegex =
multiLengthDelimMatch !== null
? RegExp(
'[' +
multiLengthDelimMatch[1].split(RegExp('\\]\\[')).join('') +
']'
)
: RegExp('[' + splitterMatch[1] + ']');
}
return splitterRegex;
}
function handleNegativeNumbers(numbers) {
const negativeNumbers = numbers.filter(i => i < 0);
if (negativeNumbers.length > 0) {
throw new Error(
'Negative numbers are not allowed: ' + negativeNumbers.join(', ')
);
}
}
module.exports = StringCalculator;