Skip to content

Commit

Permalink
Improve Trie test coverage back to 100%.
Browse files Browse the repository at this point in the history
  • Loading branch information
trekhleb committed Aug 27, 2018
1 parent 4104155 commit bdf8a17
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
22 changes: 16 additions & 6 deletions src/data-structures/trie/Trie.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,27 +29,37 @@ export default class Trie {
* @return {Trie}
*/
deleteWord(word) {
function depthFirstDelete(currentNode, charIndex) {
if (charIndex >= word.length) return;
const depthFirstDelete = (currentNode, charIndex = 0) => {
if (charIndex >= word.length) {
// Return if we're trying to delete the character that is out of word's scope.
return;
}

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

if (nextNode == null) return;
if (nextNode == null) {
// Return if we're trying to delete a word that has not been added to the Trie.
return;
}

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

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

// childNode is deleted only if:
// - childNode has NO children
// - childNode.isCompleteWord === false
currentNode.removeChild(character);
}
};

// Start depth-first deletion from the head node.
depthFirstDelete(this.head);

depthFirstDelete(this.head, 0);
return this;
}

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

// Try to delete not-existing word first.
trie.deleteWord('carpool');
expect(trie.doesWordExist('carpet')).toBe(true);
expect(trie.doesWordExist('car')).toBe(true);
expect(trie.doesWordExist('cart')).toBe(true);
expect(trie.doesWordExist('cat')).toBe(true);

trie.deleteWord('carpet');
expect(trie.doesWordExist('carpet')).toEqual(false);
expect(trie.doesWordExist('car')).toEqual(true);
Expand Down

0 comments on commit bdf8a17

Please sign in to comment.