mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-26 07:01:18 +08:00
Simplify deletion method of TrieNode.
This commit is contained in:
parent
a7ffba157c
commit
4104155182
@ -42,20 +42,16 @@ export default class TrieNode {
|
|||||||
* @return {TrieNode}
|
* @return {TrieNode}
|
||||||
*/
|
*/
|
||||||
removeChild(character) {
|
removeChild(character) {
|
||||||
function isSafeToDelete(node) {
|
|
||||||
return (
|
|
||||||
node
|
|
||||||
&& !node.isCompleteWord
|
|
||||||
&& node.children.getKeys().length === 0
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const childNode = this.getChild(character);
|
const childNode = this.getChild(character);
|
||||||
|
|
||||||
// delete childNode only if:
|
// Delete childNode only if:
|
||||||
// - childNode has NO children
|
// - childNode has NO children,
|
||||||
// - childNode.isCompleteWord === false
|
// - childNode.isCompleteWord === false.
|
||||||
if (isSafeToDelete(childNode)) {
|
if (
|
||||||
|
childNode
|
||||||
|
&& !childNode.isCompleteWord
|
||||||
|
&& !childNode.hasChildren()
|
||||||
|
) {
|
||||||
this.children.delete(character);
|
this.children.delete(character);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -70,6 +66,14 @@ export default class TrieNode {
|
|||||||
return this.children.has(character);
|
return this.children.has(character);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check whether current TrieNode has children or not.
|
||||||
|
* @return {boolean}
|
||||||
|
*/
|
||||||
|
hasChildren() {
|
||||||
|
return this.children.getKeys().length !== 0;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return {string[]}
|
* @return {string[]}
|
||||||
*/
|
*/
|
||||||
|
@ -30,6 +30,16 @@ describe('TrieNode', () => {
|
|||||||
expect(trieNode.getChild('b')).toBeUndefined();
|
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', () => {
|
it('should check if node has specific child', () => {
|
||||||
const trieNode = new TrieNode('c');
|
const trieNode = new TrieNode('c');
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user