Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions src/data-structures/trie/Trie.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,15 @@ export default class Trie {
* @return {Trie}
*/
deleteWord(word) {
// Use the same code-point representation as addWord and lookup.
const characters = Array.from(word);
const depthFirstDelete = (currentNode, charIndex = 0) => {
if (charIndex >= word.length) {
if (charIndex >= characters.length) {
// Return if we're trying to delete the character that is out of word's scope.
return;
}

const character = word[charIndex];
const character = characters[charIndex];
const nextNode = currentNode.getChild(character);

if (nextNode == null) {
Expand All @@ -47,7 +49,7 @@ export default class Trie {
depthFirstDelete(nextNode, charIndex + 1);

// Since we're going to delete a word let's un-mark its last character isCompleteWord flag.
if (charIndex === (word.length - 1)) {
if (charIndex === (characters.length - 1)) {
nextNode.isCompleteWord = false;
}

Expand Down
20 changes: 20 additions & 0 deletions src/data-structures/trie/__test__/Trie.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,26 @@ describe('Trie', () => {
expect(trie.doesWordExist('cart')).toBe(false);
});

it('should delete words containing supplementary Unicode characters', () => {
const trie = new Trie();
const words = ['😀', '😀a', '😀b', 'a😀', 'a😀b', '𐐀'];
words.forEach((word) => trie.addWord(word));

expect(trie.deleteWord('😀c')).toBe(trie);
words.forEach((word) => expect(trie.doesWordExist(word)).toBe(true));

words.forEach((word, index) => {
expect(trie.deleteWord(word)).toBe(trie);
words.slice(0, index + 1).forEach((deleted) => {
expect(trie.doesWordExist(deleted)).toBe(false);
});
words.slice(index + 1).forEach((remaining) => {
expect(trie.doesWordExist(remaining)).toBe(true);
});
});
expect(trie.head.suggestChildren()).toEqual([]);
});

it('should suggests next characters', () => {
const trie = new Trie();

Expand Down