Skip to content

Commit

Permalink
feat(treeMap): get last entry (highest value)
Browse files Browse the repository at this point in the history
  • Loading branch information
amejiarosario committed Oct 3, 2020
1 parent b047c23 commit 249de5d
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/data-structures/maps/tree-maps/tree-map.js
Expand Up @@ -18,6 +18,11 @@ const Tree = require('../../trees/red-black-tree'); // fast insertion
* allocate memory beforehand (e.g. HashMap鈥檚 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
@@ -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 },
]);
});
});
});
});

0 comments on commit 249de5d

Please sign in to comment.