Skip to content

Commit 4104155

Browse files
committedAug 27, 2018
Simplify deletion method of TrieNode.
1 parent a7ffba1 commit 4104155

File tree

2 files changed

+26
-12
lines changed

2 files changed

+26
-12
lines changed
 

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

+16-12
Original file line numberDiff line numberDiff line change
@@ -42,20 +42,16 @@ export default class TrieNode {
4242
* @return {TrieNode}
4343
*/
4444
removeChild(character) {
45-
function isSafeToDelete(node) {
46-
return (
47-
node
48-
&& !node.isCompleteWord
49-
&& node.children.getKeys().length === 0
50-
);
51-
}
52-
5345
const childNode = this.getChild(character);
5446

55-
// delete childNode only if:
56-
// - childNode has NO children
57-
// - childNode.isCompleteWord === false
58-
if (isSafeToDelete(childNode)) {
47+
// Delete childNode only if:
48+
// - childNode has NO children,
49+
// - childNode.isCompleteWord === false.
50+
if (
51+
childNode
52+
&& !childNode.isCompleteWord
53+
&& !childNode.hasChildren()
54+
) {
5955
this.children.delete(character);
6056
}
6157

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

69+
/**
70+
* Check whether current TrieNode has children or not.
71+
* @return {boolean}
72+
*/
73+
hasChildren() {
74+
return this.children.getKeys().length !== 0;
75+
}
76+
7377
/**
7478
* @return {string[]}
7579
*/

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

+10
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,16 @@ describe('TrieNode', () => {
3030
expect(trieNode.getChild('b')).toBeUndefined();
3131
});
3232

33+
it('should check if node has children', () => {
34+
const trieNode = new TrieNode('c');
35+
36+
expect(trieNode.hasChildren()).toBe(false);
37+
38+
trieNode.addChild('a');
39+
40+
expect(trieNode.hasChildren()).toBe(true);
41+
});
42+
3343
it('should check if node has specific child', () => {
3444
const trieNode = new TrieNode('c');
3545

0 commit comments

Comments
 (0)
Please sign in to comment.