From e572de63cb715afc2aed821a77f881c23036ebd4 Mon Sep 17 00:00:00 2001 From: Oleksii Trekhleb Date: Thu, 31 May 2018 07:37:31 +0300 Subject: [PATCH] Create getters and setters for meta data in binary tree node. --- src/data-structures/tree/BinaryTreeNode.js | 25 ++++++++++++++++++- .../tree/__test__/BinaryTreeNode.test.js | 19 ++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/data-structures/tree/BinaryTreeNode.js b/src/data-structures/tree/BinaryTreeNode.js index fbd53e70..13e0662c 100644 --- a/src/data-structures/tree/BinaryTreeNode.js +++ b/src/data-structures/tree/BinaryTreeNode.js @@ -5,7 +5,7 @@ export default class BinaryTreeNode { * @param {*} [value] - node value. * @param {Object} meta - any meta information that needs to be attached to the node. */ - constructor(value = null, meta = null) { + constructor(value = null, meta = {}) { this.left = null; this.right = null; this.parent = null; @@ -157,6 +157,29 @@ export default class BinaryTreeNode { return traverse; } + /** + * @param {string} property + * @param {*} value + * @return {BinaryTreeNode} + */ + setMeta(property, value) { + this.meta[property] = value; + + return this; + } + + /** + * @param property + * @return {*} + */ + getMeta(property) { + if (!this.meta || !Object.prototype.hasOwnProperty.call(this.meta, property)) { + return null; + } + + return this.meta[property]; + } + /** * @return {string} */ diff --git a/src/data-structures/tree/__test__/BinaryTreeNode.test.js b/src/data-structures/tree/__test__/BinaryTreeNode.test.js index ea0dde6c..fd50479c 100644 --- a/src/data-structures/tree/__test__/BinaryTreeNode.test.js +++ b/src/data-structures/tree/__test__/BinaryTreeNode.test.js @@ -204,4 +204,23 @@ describe('BinaryTreeNode', () => { expect(redNode.meta.color).toBe('red'); expect(blackNode.meta.color).toBe('black'); }); + + it('should be possible to use get/set methods to change node meta information', () => { + const redNode = new BinaryTreeNode(1, { color: 'red' }); + const blackNode = new BinaryTreeNode(2, { color: 'black' }); + + expect(redNode.getMeta('color')).toBe('red'); + expect(blackNode.getMeta('color')).toBe('black'); + + redNode.setMeta('size', 8); + + expect(redNode.getMeta('size')).toBe(8); + expect(redNode.getMeta('color')).toBe('red'); + expect(redNode.getMeta('not_existing')).toBeNull(); + + // It must also be possible to override meta information. + redNode.setMeta('color', 'blue'); + expect(redNode.getMeta('size')).toBe(8); + expect(redNode.getMeta('color')).toBe('blue'); + }); });