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
import { getAllWords } from "https://esm.town/v/jdan/getAllWords";
export async function wordsMatching(input: string) {
// the count of each letter in the input
const inputCount = input
.split("")
.reduce((acc, letter) => {
acc[letter] = (acc[letter] || 0) + 1;
return acc;
}, {} as Record<string, number>);
const allWords = await getAllWords();
return allWords.filter((word) => {
// return true if `word` can be made out of the letters in `input`
// Optimization: index words this way when populating the dictionary
const wordCount = word
.split("")
.reduce((acc, letter) => {
acc[letter] = (acc[letter] || 0) + 1;
return acc;
}, {} as Record<string, number>);
return Object.keys(wordCount).every((letter) => {
return inputCount[letter] >= wordCount[letter];
});
}).sort((a, b) => {
// Sort shortest first, then alphabetically
if (a.length > b.length) {
return 1;
} else if (a.length < b.length) {
return -1;
} else {
return a < b ? -1 : 1;
}
});
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
May 19, 2024