-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram2.js
More file actions
47 lines (41 loc) · 815 Bytes
/
Copy pathprogram2.js
File metadata and controls
47 lines (41 loc) · 815 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
var fs=require('fs');
const flag = process.argv[2]
const input = process.argv[3]
const isConvertHex = flag.indexOf('x') >= 0
const isFile = flag.indexOf('f') >= 0
const digitRegex = /\d$/
const mapping = (a) => {
var parsed = 0
if (isConvertHex) {
parsed = parseInt(a,16)
if ( isNaN(parsed) ) {
throw "Invalid Parameter"
}
}
else{
const matched = a.match(digitRegex)
parsed = matched === null ? 0: parseInt(a)
}
return parsed;
}
const sum = (input) => {
var output = 0
try{
var inputSequence = input.split("").map(mapping)
output = inputSequence.reduce((acc,val) => acc+val)
}
catch(e) {
output = 0
}
finally {
return output
}
}
if(isFile)
{
var contents=fs.readFileSync(input, 'utf8')
console.log(sum(contents))
}
else{
console.log(sum(input))
}