Skip to content

Commit e572de6

Browse files
committed
Create getters and setters for meta data in binary tree node.
1 parent 02d7abc commit e572de6

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

src/data-structures/tree/BinaryTreeNode.js

+24-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ export default class BinaryTreeNode {
55
* @param {*} [value] - node value.
66
* @param {Object} meta - any meta information that needs to be attached to the node.
77
*/
8-
constructor(value = null, meta = null) {
8+
constructor(value = null, meta = {}) {
99
this.left = null;
1010
this.right = null;
1111
this.parent = null;
@@ -157,6 +157,29 @@ export default class BinaryTreeNode {
157157
return traverse;
158158
}
159159

160+
/**
161+
* @param {string} property
162+
* @param {*} value
163+
* @return {BinaryTreeNode}
164+
*/
165+
setMeta(property, value) {
166+
this.meta[property] = value;
167+
168+
return this;
169+
}
170+
171+
/**
172+
* @param property
173+
* @return {*}
174+
*/
175+
getMeta(property) {
176+
if (!this.meta || !Object.prototype.hasOwnProperty.call(this.meta, property)) {
177+
return null;
178+
}
179+
180+
return this.meta[property];
181+
}
182+
160183
/**
161184
* @return {string}
162185
*/

src/data-structures/tree/__test__/BinaryTreeNode.test.js

+19
Original file line numberDiff line numberDiff line change
@@ -204,4 +204,23 @@ describe('BinaryTreeNode', () => {
204204
expect(redNode.meta.color).toBe('red');
205205
expect(blackNode.meta.color).toBe('black');
206206
});
207+
208+
it('should be possible to use get/set methods to change node meta information', () => {
209+
const redNode = new BinaryTreeNode(1, { color: 'red' });
210+
const blackNode = new BinaryTreeNode(2, { color: 'black' });
211+
212+
expect(redNode.getMeta('color')).toBe('red');
213+
expect(blackNode.getMeta('color')).toBe('black');
214+
215+
redNode.setMeta('size', 8);
216+
217+
expect(redNode.getMeta('size')).toBe(8);
218+
expect(redNode.getMeta('color')).toBe('red');
219+
expect(redNode.getMeta('not_existing')).toBeNull();
220+
221+
// It must also be possible to override meta information.
222+
redNode.setMeta('color', 'blue');
223+
expect(redNode.getMeta('size')).toBe(8);
224+
expect(redNode.getMeta('color')).toBe('blue');
225+
});
207226
});

0 commit comments

Comments
 (0)