Skip to content

Commit ca263ea

Browse files
authored
Create HackReactor - Count All Characters.js
1 parent c4d7691 commit ca263ea

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
Direction: Given a string, "countAllCharacters" returns an object where each key is a character in the given string.
3+
The value of each key should be how many times each character appeared in the given string.
4+
*/
5+
6+
/* I hashed this code out in under 3 minutes:
7+
8+
function countAllCharacters(str) {
9+
var result = { };
10+
for (let i = 0; i < str.length; i++) {
11+
if (result.hasOwnProperty(str[i])) {
12+
result[str[i]]++;
13+
} else {
14+
result[str[i]] = 1;
15+
}
16+
}
17+
return result;
18+
}
19+
countAllCharacters("banana");
20+
21+
*/
22+
23+
// Refactored to this code:
24+
25+
function countAllCharacters(str) {
26+
var result = { };
27+
str.replace(/[\s\S]/g, function(i) {
28+
result[i] = (result.hasOwnProperty(i)) ? result[i]+1 : 1; });
29+
return result;
30+
}
31+
countAllCharacters("banana");
32+
// test output: { b: 1, a: 3, n: 2 }
33+
34+
35+
36+
37+
38+
39+
40+

0 commit comments

Comments
 (0)