diff --git a/src/data-structures/trie/Trie.js b/src/data-structures/trie/Trie.js index bd618d20f4..5e2eac2334 100644 --- a/src/data-structures/trie/Trie.js +++ b/src/data-structures/trie/Trie.js @@ -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) { @@ -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; } diff --git a/src/data-structures/trie/__test__/Trie.test.js b/src/data-structures/trie/__test__/Trie.test.js index 4d60ad9c0c..8b883f36f4 100644 --- a/src/data-structures/trie/__test__/Trie.test.js +++ b/src/data-structures/trie/__test__/Trie.test.js @@ -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();