Skip to content

Commit e30bb34

Browse files
committed
feat(treeMap): get last entry (highest value)
1 parent b047c23 commit e30bb34

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/data-structures/maps/tree-maps/tree-map.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ const Tree = require('../../trees/red-black-tree'); // fast insertion
1818
* allocate memory beforehand (e.g. HashMap’s initial capacity)
1919
* nor you have to rehash when is getting full.
2020
*
21+
* Implementations in other languages:
22+
* Java: https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/TreeMap.html
23+
* C++: https://en.cppreference.com/w/cpp/container/map
24+
* Python: none
25+
*
2126
*/
2227
class TreeMap {
2328
// tag::constructor[]
@@ -92,6 +97,16 @@ class TreeMap {
9297
}
9398
// end::delete[]
9499

100+
lastEntry() {
101+
const node = this.tree.getRightmost();
102+
return node ? [node.value, node.data()] : [];
103+
}
104+
105+
firstEntry() {
106+
const node = this.tree.getLeftmost();
107+
return node ? [node.value, node.data()] : [];
108+
}
109+
95110
// tag::iterators[]
96111
/**
97112
* Default iterator for this map
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// some parts tested on src/data-structures/maps/map.spec.js
2+
3+
const TreeMap = require('./tree-map');
4+
5+
describe('TreeMap: keep values sorted', () => {
6+
let map;
7+
8+
beforeEach(() => {
9+
map = new TreeMap();
10+
});
11+
12+
describe('when map is empty', () => {
13+
describe('.lastEntry and .firstEntry', () => {
14+
it('should get last/first entry', () => {
15+
expect(map.lastEntry()).toEqual([]);
16+
expect(map.firstEntry()).toEqual([]);
17+
});
18+
});
19+
});
20+
21+
describe('when map has entries', () => {
22+
beforeEach(() => {
23+
map.set(20, { title: '3sum', passed: true });
24+
map.set(30, { title: '3sum', passed: false });
25+
map.set(10, { title: '2sum', passed: true });
26+
map.set(5, { title: '4sum', passed: false });
27+
});
28+
29+
describe('.lastEntry and .firstEntry', () => {
30+
it('should get last/first entry', () => {
31+
expect(map.lastEntry()).toEqual([
32+
30,
33+
{ title: '3sum', passed: false },
34+
]);
35+
36+
expect(map.firstEntry()).toEqual([
37+
5,
38+
{ title: '4sum', passed: false },
39+
]);
40+
});
41+
});
42+
});
43+
});

0 commit comments

Comments
 (0)