File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments