Skip to content

Commit 5bf850c

Browse files
committed
Add .peek() method
Fixes #6
1 parent d7effc9 commit 5bf850c

File tree

4 files changed

+30
-0
lines changed

4 files changed

+30
-0
lines changed

index.d.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,13 @@ export default class Queue<ValueType> implements Iterable<ValueType> {
4747
*/
4848
dequeue(): ValueType | undefined;
4949

50+
/**
51+
Get the next value in the queue without removing it.
52+
53+
@returns The value or `undefined` if the queue is empty.
54+
*/
55+
peek(): ValueType | undefined;
56+
5057
/**
5158
Clear the queue.
5259
*/

index.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ export default class Queue {
4646
return current.value;
4747
}
4848

49+
peek() {
50+
return this.#head?.value;
51+
}
52+
4953
clear() {
5054
this.#head = undefined;
5155
this.#tail = undefined;

readme.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,12 @@ Remove the next value in the queue.
5151

5252
Returns the removed value or `undefined` if the queue is empty.
5353

54+
#### `.peek()`
55+
56+
Get the next value in the queue without removing it.
57+
58+
Returns the value or `undefined` if the queue is empty.
59+
5460
#### `.clear()`
5561

5662
Clear the queue.

test.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,19 @@ test('.dequeue()', t => {
2020
t.is(queue.dequeue(), undefined);
2121
});
2222

23+
test('.peek()', t => {
24+
const queue = new Queue();
25+
t.is(queue.peek(), undefined);
26+
queue.enqueue('🦄');
27+
t.is(queue.peek(), '🦄');
28+
queue.enqueue('🌈');
29+
t.is(queue.peek(), '🦄');
30+
queue.dequeue();
31+
t.is(queue.peek(), '🌈');
32+
queue.dequeue();
33+
t.is(queue.peek(), undefined);
34+
});
35+
2336
test('.clear()', t => {
2437
const queue = new Queue();
2538
queue.clear();

0 commit comments

Comments
 (0)