diff --git a/README.md b/README.md index e719a85..b931b14 100644 --- a/README.md +++ b/README.md @@ -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) @@ -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): diff --git a/src/heapify.ts b/src/heapify.ts index 3a31f5a..107de10 100644 --- a/src/heapify.ts +++ b/src/heapify.ts @@ -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 diff --git a/test/heapify.test.ts b/test/heapify.test.ts index a2005a7..354d9e2 100644 --- a/test/heapify.test.ts +++ b/test/heapify.test.ts @@ -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); + }) });