|
1 | | -/* |
2 | | - Given a string of characters, return the character that appears the most often. |
3 | | - Example: input = "Hello World!" return "l" |
4 | | -*/ |
5 | | -const maxCharacter = (value) => { |
6 | | - if (typeof value !== 'string') { |
7 | | - throw new TypeError('The param should be a string') |
8 | | - } else if (!value) { |
9 | | - throw new Error('The param should be a valid string') |
| 1 | +/** |
| 2 | + * @function maxCharacter |
| 3 | + * @example - Given a string of characters, return the character that appears the most often. Example: input = "Hello World!" return "l" |
| 4 | + * @param {string} str |
| 5 | + * @param {RegExp} ignorePattern - ignore the char in str that is not required |
| 6 | + * @returns {string} - char |
| 7 | + */ |
| 8 | +const maxCharacter = (str, ignorePattern) => { // initially it's count only alphabets |
| 9 | + if (typeof str !== 'string') { |
| 10 | + throw new TypeError('Argument should be a string') |
| 11 | + } else if (!str) { |
| 12 | + throw new Error('The param should be a nonempty string') |
10 | 13 | } |
11 | 14 |
|
12 | | - const occurrences = {} |
13 | | - for (let i = 0; i < value.length; i++) { |
14 | | - const char = value[i] |
15 | | - if (/\s/.test(char)) continue |
16 | | - occurrences[char] = occurrences[char] + 1 || 1 |
| 15 | + // store all char in occurrence map |
| 16 | + const occurrenceMap = new Map() |
| 17 | + |
| 18 | + for (const char of str) { |
| 19 | + if (!ignorePattern?.test(char)) { |
| 20 | + occurrenceMap.set(char, occurrenceMap.get(char) + 1 || 1) |
| 21 | + } |
17 | 22 | } |
18 | | - let maxCharacter = null |
19 | | - let maxCount = 0 |
20 | | - Object.keys(occurrences).forEach(char => { |
21 | | - if (occurrences[char] > maxCount) { |
22 | | - maxCount = occurrences[char] |
23 | | - maxCharacter = char |
| 23 | + |
| 24 | + // find the max char from the occurrence map |
| 25 | + let max = { char: '', occur: -Infinity } |
| 26 | + |
| 27 | + for (const [char, occur] of occurrenceMap) { |
| 28 | + if (occur > max.occur) { |
| 29 | + max = { char, occur } |
24 | 30 | } |
25 | | - }) |
26 | | - return maxCharacter |
| 31 | + } |
| 32 | + |
| 33 | + return max.char |
27 | 34 | } |
28 | 35 |
|
29 | | -export { maxCharacter } |
| 36 | +export default maxCharacter |
0 commit comments