-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
91 lines (70 loc) · 2.28 KB
/
Copy pathserver.js
File metadata and controls
91 lines (70 loc) · 2.28 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const add = (numberString) => {
if (numberString === "") return 0;
if (numberString.startsWith("//[")) {
const delimiter = getDelimiter(numberString);
const formattedInput = formatInput(numberString);
const numberArray = getNumbers(formattedInput, delimiter);
return sumNumbers(numberArray);
}
const normalizedNumbers = numberString.replace(/\n/g, ",");
const numberArray = normalizedNumbers.split(",");
return sumNumbers(numberArray);
};
function getNumbers(string, delimiter) {
return string.split(delimiter)
.filter(n => n !== '')
.map(n => parseInt(n));
}
function formatInput(input) {
const delimiterRegExp = /^(\/\/.*\n)/;
const matches = delimiterRegExp.exec(input);
if (matches && matches.length > 0) {
return input.replace(delimiterRegExp, '');
}
return input;
}
function getDelimiter(input) {
const delimiters = [];
const multipleDelimiterRegexp = /(?:^\/\/)?\[([^\[\]]+)\]\n?/g;
let matches = multipleDelimiterRegexp.exec(input);
while (matches !== null) {
delimiters.push(matches[1]);
matches = multipleDelimiterRegexp.exec(input);
}
if (delimiters.length > 0) {
return new RegExp('[' + delimiters.join('') + ']');
}
matches = /^\/\/(.*)\n/.exec(input);
if (matches && matches[1]) {
return matches[1];
}
return /[\n,]/;
}
function sumNumbers(numberArray) {
let sum = 0, negatives = [];
numberArray.forEach(num => {
const number = parseInt(num);
if (isNaN(number)) return; // Ignore empty strings or invalid numbers
if (number > 1000) return;
if (number < 0) {
negatives.push(number);
}
else {
sum += number;
}
});
if (negatives.length > 0) {
throw new Error("Negative numbers not allowed: " + negatives.join(", "));
}
return sum;
}
console.log(add("")); //0
console.log(add("1")); //1
console.log(add("1,5")); //6
console.log(add("1,5,6")); //12
console.log(add("1,5,6,4")); //16
console.log(add("1\n2,3")); //6
console.log(add("//;\n1;2")); //3
console.log(add("//[***]\n1***2***3")); //6
console.log(add("2+1001")); //2
console.log(add("//;\n1;2;-1")); //Negative numbers not allowed -1