Skip to content

Commit

Permalink
Simplify deletion method of TrieNode.
Browse files Browse the repository at this point in the history
  • Loading branch information
trekhleb committed Aug 27, 2018
1 parent a7ffba1 commit 4104155
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 12 deletions.
28 changes: 16 additions & 12 deletions src/data-structures/trie/TrieNode.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,16 @@ export default class TrieNode {
* @return {TrieNode}
*/
removeChild(character) {
function isSafeToDelete(node) {
return (
node
&& !node.isCompleteWord
&& node.children.getKeys().length === 0
);
}

const childNode = this.getChild(character);

// delete childNode only if:
// - childNode has NO children
// - childNode.isCompleteWord === false
if (isSafeToDelete(childNode)) {
// Delete childNode only if:
// - childNode has NO children,
// - childNode.isCompleteWord === false.
if (
childNode
&& !childNode.isCompleteWord
&& !childNode.hasChildren()
) {
this.children.delete(character);
}

Expand All @@ -70,6 +66,14 @@ export default class TrieNode {
return this.children.has(character);
}

/**
* Check whether current TrieNode has children or not.
* @return {boolean}
*/
hasChildren() {
return this.children.getKeys().length !== 0;
}

/**
* @return {string[]}
*/
Expand Down
10 changes: 10 additions & 0 deletions src/data-structures/trie/__test__/TrieNode.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@ describe('TrieNode', () => {
expect(trieNode.getChild('b')).toBeUndefined();
});

it('should check if node has children', () => {
const trieNode = new TrieNode('c');

expect(trieNode.hasChildren()).toBe(false);

trieNode.addChild('a');

expect(trieNode.hasChildren()).toBe(true);
});

it('should check if node has specific child', () => {
const trieNode = new TrieNode('c');

Expand Down

0 comments on commit 4104155

Please sign in to comment.