Simplify deletion method of TrieNode.

This commit is contained in:
Oleksii Trekhleb 2018-08-27 15:45:48 +03:00
parent a7ffba157c
commit 4104155182
2 changed files with 26 additions and 12 deletions

View File

@ -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);
}
@ -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[]}
*/

View File

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