Skip to content

Commit bdf8a17

Browse files
committedAug 27, 2018
Improve Trie test coverage back to 100%.
1 parent 4104155 commit bdf8a17

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed
 

‎src/data-structures/trie/Trie.js

+16-6
Original file line numberDiff line numberDiff line change
@@ -29,27 +29,37 @@ export default class Trie {
2929
* @return {Trie}
3030
*/
3131
deleteWord(word) {
32-
function depthFirstDelete(currentNode, charIndex) {
33-
if (charIndex >= word.length) return;
32+
const depthFirstDelete = (currentNode, charIndex = 0) => {
33+
if (charIndex >= word.length) {
34+
// Return if we're trying to delete the character that is out of word's scope.
35+
return;
36+
}
3437

3538
const character = word[charIndex];
3639
const nextNode = currentNode.getChild(character);
3740

38-
if (nextNode == null) return;
41+
if (nextNode == null) {
42+
// Return if we're trying to delete a word that has not been added to the Trie.
43+
return;
44+
}
3945

46+
// Go deeper.
4047
depthFirstDelete(nextNode, charIndex + 1);
4148

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

4654
// childNode is deleted only if:
4755
// - childNode has NO children
4856
// - childNode.isCompleteWord === false
4957
currentNode.removeChild(character);
50-
}
58+
};
59+
60+
// Start depth-first deletion from the head node.
61+
depthFirstDelete(this.head);
5162

52-
depthFirstDelete(this.head, 0);
5363
return this;
5464
}
5565

‎src/data-structures/trie/__test__/Trie.test.js

+7
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,13 @@ describe('Trie', () => {
3535
expect(trie.doesWordExist('cart')).toBe(true);
3636
expect(trie.doesWordExist('cat')).toBe(true);
3737

38+
// Try to delete not-existing word first.
39+
trie.deleteWord('carpool');
40+
expect(trie.doesWordExist('carpet')).toBe(true);
41+
expect(trie.doesWordExist('car')).toBe(true);
42+
expect(trie.doesWordExist('cart')).toBe(true);
43+
expect(trie.doesWordExist('cat')).toBe(true);
44+
3845
trie.deleteWord('carpet');
3946
expect(trie.doesWordExist('carpet')).toEqual(false);
4047
expect(trie.doesWordExist('car')).toEqual(true);

0 commit comments

Comments
 (0)
Please sign in to comment.