File tree 2 files changed +43
-1
lines changed
2 files changed +43
-1
lines changed Original file line number Diff line number Diff line change @@ -5,7 +5,7 @@ export default class BinaryTreeNode {
5
5
* @param {* } [value] - node value.
6
6
* @param {Object } meta - any meta information that needs to be attached to the node.
7
7
*/
8
- constructor ( value = null , meta = null ) {
8
+ constructor ( value = null , meta = { } ) {
9
9
this . left = null ;
10
10
this . right = null ;
11
11
this . parent = null ;
@@ -157,6 +157,29 @@ export default class BinaryTreeNode {
157
157
return traverse ;
158
158
}
159
159
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
+
160
183
/**
161
184
* @return {string }
162
185
*/
Original file line number Diff line number Diff line change @@ -204,4 +204,23 @@ describe('BinaryTreeNode', () => {
204
204
expect ( redNode . meta . color ) . toBe ( 'red' ) ;
205
205
expect ( blackNode . meta . color ) . toBe ( 'black' ) ;
206
206
} ) ;
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
+ } ) ;
207
226
} ) ;
You can’t perform that action at this time.
0 commit comments