forked from ssitu001/toyProblemPractice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcharacterSum.js
57 lines (44 loc) · 910 Bytes
/
characterSum.js
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
//characterSum.js
// Given a string of arbitrary size, convert each character
// into its integer equivalent and sum the entirety.
// Examples
// Input Output
// str:
// "123" 6
// str:
// "0101" 2
// str:
// "so cool!!1!" 1
//iteratively
function charSum (str) {
var int = 0;
for (var i = 0; i < str.length; i++) {
if ( !isNaN(Number(str[i]))) {
int = int + Number(str[i]);
}
}
return int;
}
//with reduce
function charSum(str) {
str = str.split("");
return str.reduce( (acc, char) => {
if ( !isNaN(Number(char))) {
acc = acc + Number(char);
}
return acc;
}, 0);
}
//recursively
function charSum(str, acc) {
acc = acc || 0;
if (!str.length) {
return acc;
}
var firstChar = str.charAt(0);
if ( !isNaN(Number(firstChar))) {
acc = acc + Number(firstChar);
}
return charSum(str.slice(1), acc);
}
charSum("so cool!!1!");