-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd.js
More file actions
33 lines (26 loc) · 934 Bytes
/
add.js
File metadata and controls
33 lines (26 loc) · 934 Bytes
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
const DEFAULT_DELIMITER = ','
const isValidInput = (input) => {
if(typeof input !== 'string') return false
if(input.length < 1) return false
return true
}
const normalizeDelimiters = (input, defaultDelimiter) => input.replace(/[\n\r]/g, defaultDelimiter)
const defineDelimiter = (input) => {
const matches = input.match(/^\/\/(\S+)[\n\r]/)
if (matches) {
const newDelimiter = matches[1]
return [newDelimiter, input.slice(matches[0].length - 1)]
}
return [DEFAULT_DELIMITER, input]
}
const add = (numbers) => {
if (!isValidInput(numbers)) return 0
const [delimiter, cleanedInput] = defineDelimiter(numbers)
const intArray = normalizeDelimiters(cleanedInput, delimiter).split(delimiter)
if (intArray.length === 1) return Number(intArray[0])
const reducer = (accumulator, curentValue) => {
return accumulator + Number(curentValue)
}
return intArray.reduce(reducer, 0)
}
export default add