Improve Trie test coverage back to 100%.

This commit is contained in:
Oleksii Trekhleb 2018-08-27 15:54:55 +03:00
parent 4104155182
commit bdf8a174eb
2 changed files with 23 additions and 6 deletions

View File

@ -29,17 +29,25 @@ 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;
}
@ -47,9 +55,11 @@ export default class Trie {
// - 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;
}

View File

@ -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);