Last active
December 3, 2025 17:39
-
-
Save PierreTurnbull/8b5d3dbe6b552ee9fa98f8d1d5e34ee8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function getHighestFrequencies(sentence: string, n: number) { | |
| const words = sentence.split(/ +/) | |
| const frequencyByWord: Record<string, number> = {} | |
| for (const word of words) { | |
| frequencyByWord[word] = (frequencyByWord[word] || 0) + 1 | |
| } | |
| const entries = Object.entries(frequencyByWord) | |
| entries.sort((a, b) => { | |
| const aWord = a[0] | |
| const aFrequency = a[1] | |
| const bWord = b[0] | |
| const bFrequency = b[1] | |
| // Attempt sorting by frequency. | |
| const frequencyDiff = bFrequency - aFrequency | |
| if (frequencyDiff !== 0) { | |
| return frequencyDiff | |
| } | |
| // Otherwise sort by alphabetical order. | |
| const wordDiff = aWord.localeCompare(bWord) | |
| return wordDiff | |
| }) | |
| return entries.slice(0, n) | |
| } | |
| function deepAssert(name: string, received: unknown, expected: unknown) { | |
| const stringifiedA = JSON.stringify(received) | |
| const stringifiedB = JSON.stringify(expected) | |
| console.group(name) | |
| if (stringifiedA !== stringifiedB) { | |
| console.error(`FAIL\nExpected: ${expected}\nReceived: ${received}`) | |
| } else { | |
| console.info("OK") | |
| } | |
| console.groupEnd() | |
| } | |
| deepAssert( | |
| "Base", | |
| getHighestFrequencies("a", 1), | |
| [["a", 1]], | |
| ) | |
| deepAssert( | |
| "Excessive spacing", | |
| getHighestFrequencies("a b", 3), | |
| [["a", 1], ["b", 1]], | |
| ) | |
| deepAssert( | |
| "Sliced result", | |
| getHighestFrequencies("a b", 1), | |
| [["a", 1]], | |
| ) | |
| deepAssert( | |
| "Not enough words", | |
| getHighestFrequencies("a", 2), | |
| [["a", 1]], | |
| ) | |
| deepAssert( | |
| "Multiple-character word", | |
| getHighestFrequencies("ab", 1), | |
| [["ab", 1]], | |
| ) | |
| deepAssert( | |
| "Frequency sorting", | |
| getHighestFrequencies("one three three three two two", 3), | |
| [["three", 3], ["two", 2], ["one", 1]], | |
| ) | |
| deepAssert( | |
| "Alphabetical sorting", | |
| getHighestFrequencies("a c b", 3), | |
| [["a", 1], ["b", 1], ["c", 1]], | |
| ) | |
| deepAssert( | |
| "Frequency sorting over alphabetical sorting", | |
| getHighestFrequencies("a b b", 2), | |
| [["b", 2], ["a", 1]], | |
| ) | |
| deepAssert( | |
| "Mix", | |
| getHighestFrequencies("bar baz foo foo zblah zblah zblah baz toto bar", 3), | |
| [["zblah", 3],["bar", 2],["baz", 2]], | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment