|
1 |
| -import { partition } from 'lodash'; |
2 | 1 | import { Char, ICharTrie } from '../types/charTrie';
|
3 | 2 |
|
4 | 3 | const leafNode = new Map() as ICharTrie;
|
5 | 4 |
|
| 5 | +function groupWordsByHeadChar( |
| 6 | + words: string[], |
| 7 | + firstChar: string |
| 8 | +): [string[], string[]] { |
| 9 | + const matched: string[] = []; |
| 10 | + const missed: string[] = []; |
| 11 | + |
| 12 | + words.forEach(word => { |
| 13 | + if (word[0] === firstChar) { |
| 14 | + matched.push(word); |
| 15 | + } else { |
| 16 | + missed.push(word); |
| 17 | + } |
| 18 | + }); |
| 19 | + |
| 20 | + return [matched, missed]; |
| 21 | +} |
| 22 | + |
6 | 23 | /**
|
7 | 24 | * Arrange a head character and its suffixes into a trie.
|
8 | 25 | * Flatten leaves of the character trie containing a single letter.
|
@@ -38,13 +55,13 @@ function buildUnique(words: string[]): ICharTrie {
|
38 | 55 | if (wordToMatch === '') {
|
39 | 56 | // End of the target word reached. Include an empty string to signify that
|
40 | 57 | // a word ends at this spot, and group any remaining words in the trie.
|
41 |
| - const [, nonEmptyWords] = partition(words, word => word === ''); |
| 58 | + const nonEmptyWords = words.filter(word => word !== ''); |
42 | 59 | return new Map([['', leafNode], ...build(nonEmptyWords)]) as ICharTrie;
|
43 | 60 | }
|
44 | 61 |
|
45 | 62 | // Begin a new trie containing all words starting with the same letter as wordToMatch
|
46 | 63 | const charToMatch = wordToMatch[0];
|
47 |
| - const [wordsMatched, wordsMissed] = partition(words, ['[0]', charToMatch]); |
| 64 | + const [wordsMatched, wordsMissed] = groupWordsByHeadChar(words, charToMatch); |
48 | 65 |
|
49 | 66 | const tailsMatched = wordsMatched.map(word => word.substring(1));
|
50 | 67 | const tailsMatchedGrouped = build(tailsMatched);
|
|
0 commit comments