From eac3e81a21f7f26cd8f66ca1981c411b71a0f1de Mon Sep 17 00:00:00 2001 From: Kevin Brewer Date: Sat, 25 Aug 2018 05:27:44 -0500 Subject: [PATCH] Fix TrieNode.addChild so substrings get marked as complete words (#177) --- src/data-structures/trie/TrieNode.js | 5 ++++- src/data-structures/trie/__test__/Trie.test.js | 3 +++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/data-structures/trie/TrieNode.js b/src/data-structures/trie/TrieNode.js index cf89fdd6..f24910f1 100644 --- a/src/data-structures/trie/TrieNode.js +++ b/src/data-structures/trie/TrieNode.js @@ -29,7 +29,10 @@ export default class TrieNode { this.children.set(character, new TrieNode(character, isCompleteWord)); } - return this.children.get(character); + const childNode = this.children.get(character); + childNode.isCompleteWord = childNode.isCompleteWord || isCompleteWord; + + return childNode; } /** diff --git a/src/data-structures/trie/__test__/Trie.test.js b/src/data-structures/trie/__test__/Trie.test.js index b66db94a..194ca16a 100644 --- a/src/data-structures/trie/__test__/Trie.test.js +++ b/src/data-structures/trie/__test__/Trie.test.js @@ -41,11 +41,14 @@ describe('Trie', () => { trie.addWord('cat'); trie.addWord('cats'); + trie.addWord('carpet'); trie.addWord('car'); trie.addWord('caption'); expect(trie.doesWordExist('cat')).toBe(true); expect(trie.doesWordExist('cats')).toBe(true); + expect(trie.doesWordExist('carpet')).toBe(true); + expect(trie.doesWordExist('car')).toBe(true); expect(trie.doesWordExist('cap')).toBe(false); expect(trie.doesWordExist('call')).toBe(false); });