-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHackReactor-Count_All_Characters.js
More file actions
50 lines (37 loc) · 1.14 KB
/
HackReactor-Count_All_Characters.js
File metadata and controls
50 lines (37 loc) · 1.14 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
/*
Direction: Given a string, "countAllCharacters" returns an object where each key is a character in the given string.
The value of each key should be how many times each character appeared in the given string.
*/
/* I hashed this code out in under 3 minutes:
function countAllCharacters(str) {
var result = { };
for (let i = 0; i < str.length; i++) {
if (result.hasOwnProperty(str[i])) {
result[str[i]]++;
} else {
result[str[i]] = 1;
}
}
return result;
}
countAllCharacters("banana");
*/
// Refactored to this code:
function countAllCharacters(str) {
var result = { };
str.replace(/[\s\S]/g, function(i) {
result[i] = (result.hasOwnProperty(i)) ? result[i]+1 : 1; });
return result;
}
countAllCharacters("banana");
// test output: { b: 1, a: 3, n: 2 }
// Another refactored solution using Map() instead of an Object
function countAllCharacters(str) {
let resultMap = new Map();
str.replace(/[\s\S]/g, function(i) {
let val = resultMap.has(i) ? resultMap.get(i) + 1 : 1;
resultMap.set(i, val);
});
return resultMap;
}
countAllCharacters("banana");