1 // Copyright Jerome Benoit. 2023. All Rights Reserved.
11 public constructor (value
: T
) {
18 * Implemented with a doubly linked list.
20 * @typeParam T - Type of deque values.
23 export class Deque
<T
> {
24 private head
?: Node
<T
>
25 private tail
?: Node
<T
>
26 /** The size of the deque. */
28 /** The maximum size of the deque. */
29 public maxSize
!: number
31 public constructor () {
36 * Appends a value to the deque.
38 * @param value - Value to append.
39 * @returns The new size of the queue.
41 public push (value
: T
): number {
42 const node
= new Node(value
)
43 if (this.tail
== null) {
44 this.head
= this.tail
= node
47 this.tail
= this.tail
.next
= node
49 return this.incrementSize()
53 * Prepends a value to the deque.
55 * @param value - Value to prepend.
56 * @returns The new size of the queue.
58 public unshift (value
: T
): number {
59 const node
= new Node(value
)
60 if (this.head
== null) {
61 this.head
= this.tail
= node
64 this.head
= this.head
.prev
= node
66 return this.incrementSize()
70 * Pops a value from the deque.
72 * @returns The popped value or `undefined` if the deque is empty.
74 public pop (): T
| undefined {
75 if (this.head
== null) {
78 const tail
= this.tail
79 this.tail
= (this.tail
as Node
<T
>).prev
80 if (this.tail
== null) {
83 this.tail
.next
= undefined
90 * Shifts a value from the deque.
92 * @returns The shifted value or `undefined` if the deque is empty.
94 public shift (): T
| undefined {
95 if (this.head
== null) {
98 const head
= this.head
99 this.head
= this.head
.next
100 if (this.head
== null) {
101 this.tail
= undefined
103 this.head
.prev
= undefined
110 * Peeks at the first value.
111 * @returns The first value or `undefined` if the deque is empty.
113 public peekFirst (): T
| undefined {
114 return this.head
?.value
118 * Peeks at the last value.
119 * @returns The last value or `undefined` if the deque is empty.
121 public peekLast (): T
| undefined {
122 return this.tail
?.value
128 public clear (): void {
129 this.head
= undefined
130 this.tail
= undefined
136 * Returns an iterator for the deque.
138 * @returns An iterator for the deque.
139 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
141 [Symbol
.iterator
] (): Iterator
<T
> {
155 node
= node
.next
as Node
<T
>
162 * Returns an backward iterator for the deque.
164 * @returns An backward iterator for the deque.
165 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
167 backward (): Iterable
<T
> {
169 [Symbol
.iterator
]: (): Iterator
<T
> => {
183 node
= node
.prev
as Node
<T
>
191 private incrementSize (): number {
193 if (this.size
> this.maxSize
) {
194 this.maxSize
= this.size