-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
letter-count.js
54 lines (48 loc) · 1.4 KB
/
letter-count.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
/*
Create a function `letterCount` that accepts a string, and finds the number of times each letter
occurs in the string. For example, given the word "apple", letterCount("apple") should count all
occurrences of the letters "a", "p", "l" and "e" and then return the following output:
```javascript
{
"a": 1,
"p": 2,
"l": 1,
"e": 1
}
```
Bonuses
- Make sure that lower case letters and upper case letters count for the same character.
- Ignore spaces, special characters, and punctuation.
- Instead of just counting letters, calculate their percent-based frequency.
See: http://www.math.cornell.edu/~mec/2003-2004/cryptography/subs/frequencies.html
```javascript
{
"a": 0.2, // percent
"p": 0.4,
"l": 0.2,
"e": 0.2
}
```
*/
// YOUR CODE HERE
function letterCount(word) {
let wordCount = {};
word = word.replace(/[^\w]/g, "");
for (letter of word) {
letter = letter.toLowerCase();
wordCount[letter] = wordCount[letter] + 1 || 1;
}
return wordCount;
}
function letterFrequency(word) {
let count = letterCount(word);
Object.keys(count).forEach(letter => {
count[letter] = count[letter] / word.length;
});
return count;
}
// console.log(letterCount("Apple"));
// console.log(letterCount("Appfffle"));
// console.log(letterCount("apple"));
// console.log(letterCount("Monic@!"));
// console.log(letterFrequency("Apple"));