-
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathcount-characters-in-your-string.js
More file actions
41 lines (37 loc) · 1.01 KB
/
count-characters-in-your-string.js
File metadata and controls
41 lines (37 loc) · 1.01 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
function count (string) {
// an object to store the counts
const counts = {};
// iterate over the letters in the string
for (let i = 0; i < string.length; i++) {
const letter = string[i];
// if the current letter is not a property in the object
// set it 0
counts[letter] = counts[letter] || 0;
// increment the current letter in the object by 1
counts[letter]++;
}
return counts;
}
function count (string) {
return Array.prototype.reduce.call(string, (counts, letter) => {
counts[letter] = counts[letter] || 0;
counts[letter]++;
return counts;
}, {});
}
function count (string) {
return string.split('').reduce((counts, letter) => {
counts[letter] = counts[letter] || 0;
counts[letter]++;
return counts;
}, {});
}
function count (string) {
return [].reduce.call(string, (counts, letter) => {
counts[letter] = counts[letter] || 0;
counts[letter]++;
return counts;
}, {});
}
console.log(count('aba'), { a: 2, b: 1 });
console.log(count(''), {});