Skip to content

feat(treeMap): get last entry (highest value) #85

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/data-structures/maps/tree-maps/tree-map.js
Original file line number Diff line number Diff line change
Expand Up @@ -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[]
Expand Down Expand Up @@ -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
Expand Down
43 changes: 43 additions & 0 deletions src/data-structures/maps/tree-maps/tree-map.spec.js
Original file line number Diff line number Diff line change
@@ -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 },
]);
});
});
});
});