diff --git a/src/data-structures/maps/tree-maps/tree-map.js b/src/data-structures/maps/tree-maps/tree-map.js index eed8bc78..10957aed 100644 --- a/src/data-structures/maps/tree-maps/tree-map.js +++ b/src/data-structures/maps/tree-maps/tree-map.js @@ -18,6 +18,11 @@ const Tree = require('../../trees/red-black-tree'); // fast insertion * allocate memory beforehand (e.g. HashMap’s initial capacity) * nor you have to rehash when is getting full. * + * Implementations in other languages: + * Java: https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/TreeMap.html + * C++: https://en.cppreference.com/w/cpp/container/map + * Python: none + * */ class TreeMap { // tag::constructor[] @@ -92,6 +97,22 @@ class TreeMap { } // end::delete[] + /** + * Get the last key/value pair (node with largest key) + */ + lastEntry() { + const node = this.tree.getRightmost(); + return node ? [node.value, node.data()] : []; + } + + /** + * Get the first key/value pair (node with smallest key) + */ + firstEntry() { + const node = this.tree.getLeftmost(); + return node ? [node.value, node.data()] : []; + } + // tag::iterators[] /** * Default iterator for this map diff --git a/src/data-structures/maps/tree-maps/tree-map.spec.js b/src/data-structures/maps/tree-maps/tree-map.spec.js new file mode 100644 index 00000000..8661207a --- /dev/null +++ b/src/data-structures/maps/tree-maps/tree-map.spec.js @@ -0,0 +1,43 @@ +// some parts tested on src/data-structures/maps/map.spec.js + +const TreeMap = require('./tree-map'); + +describe('TreeMap: keep values sorted', () => { + let map; + + beforeEach(() => { + map = new TreeMap(); + }); + + describe('when map is empty', () => { + describe('.lastEntry and .firstEntry', () => { + it('should get last/first entry', () => { + expect(map.lastEntry()).toEqual([]); + expect(map.firstEntry()).toEqual([]); + }); + }); + }); + + describe('when map has entries', () => { + beforeEach(() => { + map.set(20, { title: '3sum', passed: true }); + map.set(30, { title: '3sum', passed: false }); + map.set(10, { title: '2sum', passed: true }); + map.set(5, { title: '4sum', passed: false }); + }); + + describe('.lastEntry and .firstEntry', () => { + it('should get last/first entry', () => { + expect(map.lastEntry()).toEqual([ + 30, + { title: '3sum', passed: false }, + ]); + + expect(map.firstEntry()).toEqual([ + 5, + { title: '4sum', passed: false }, + ]); + }); + }); + }); +});