Use Map for TrieNode children (#27)

This commit is contained in:
Cyril Auburtin 2018-05-29 05:13:12 +02:00 committed by Oleksii Trekhleb
parent 30ae3230d1
commit b1a613e03e
2 changed files with 9 additions and 13 deletions

View File

@ -2,35 +2,31 @@ export default class TrieNode {
constructor(character, isCompleteWord = false) { constructor(character, isCompleteWord = false) {
this.character = character; this.character = character;
this.isCompleteWord = isCompleteWord; this.isCompleteWord = isCompleteWord;
this.children = {}; this.children = new Map();
} }
getChild(character) { getChild(character) {
if (!Object.prototype.hasOwnProperty.call(this.children, character)) { return this.children.get(character);
return null;
}
return this.children[character];
} }
addChild(character, isCompleteWord = false) { addChild(character, isCompleteWord = false) {
if (!this.children[character]) { if (!this.children.has(character)) {
this.children[character] = new TrieNode(character, isCompleteWord); this.children.set(character, new TrieNode(character, isCompleteWord));
} }
return this.children[character]; return this.children.get(character);
} }
hasChild(character) { hasChild(character) {
return !!this.children[character]; return this.children.has(character);
} }
suggestChildren() { suggestChildren() {
return Object.keys(this.children); return [...this.children.keys()];
} }
toString() { toString() {
let childrenAsString = Object.keys(this.children).toString(); let childrenAsString = this.suggestChildren().toString();
childrenAsString = childrenAsString ? `:${childrenAsString}` : ''; childrenAsString = childrenAsString ? `:${childrenAsString}` : '';
const isCompleteString = this.isCompleteWord ? '*' : ''; const isCompleteString = this.isCompleteWord ? '*' : '';

View File

@ -26,7 +26,7 @@ describe('TrieNode', () => {
expect(trieNode.getChild('a').toString()).toBe('a'); expect(trieNode.getChild('a').toString()).toBe('a');
expect(trieNode.getChild('o').toString()).toBe('o'); expect(trieNode.getChild('o').toString()).toBe('o');
expect(trieNode.getChild('b')).toBeNull(); expect(trieNode.getChild('b')).toBeUndefined();
}); });
it('should check if node has specific child', () => { it('should check if node has specific child', () => {