Skip to content
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

Feat/get priority #52

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ Heapify's design strives for reliability, with strong test coverage and focus on
- [pop()](#pop)
- [push(key, priority)](#pushkey-priority)
- [size](#size)
- [getPriority(key)](#getpriority-key)
- [Benchmark](#benchmark)
- [Contributing](#contributing)

Expand Down Expand Up @@ -233,6 +234,18 @@ queue.pop();
queue.size; // 0
```

### getPriority(key)

Gets the _priority_ of the given `key`.

Example:

```js
const queue = new MinQueue();
queue.push(1, 10);
queue.getPriority(1); // 10
```

## Benchmark

Here's a table comparing Heapify with other implementations (times are in milliseconds):
Expand Down
5 changes: 5 additions & 0 deletions src/heapify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,11 @@ export class MinQueue {
return this._keys[ROOT_INDEX];
}

getPriority(key: number): number | undefined {
const index = this._keys.findIndex(k => k === key);
return index === -1 ? undefined : this._priorities[index];
}

private removePoppedElement(): void {
if (this._hasPoppedElement) {
// since root element was already deleted from pop, replace with last and bubble down
Expand Down
16 changes: 16 additions & 0 deletions test/heapify.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,4 +240,20 @@ describe("MinQueue", () => {
// v0.4.0 returns 3 here
assert.strictEqual(queue.pop(), 2);
});

test("get priority of given key", () => {
const queue = new MinQueue();
queue.push(1, 10);
queue.push(2, 20);
queue.push(3, 15);
assert.strictEqual(queue.getPriority(1), 10);
assert.strictEqual(queue.getPriority(2), 20);
assert.strictEqual(queue.getPriority(3), 15);
})

test("get priority returns undefined if key not found", () => {
const queue = new MinQueue();
queue.push(1, 10);
assert.strictEqual(queue.getPriority(2), undefined);
})
});