Created
December 22, 2022 19:05
-
-
Save itacirgabral/5fd6339cd765990fdbbd3e2c78502ed5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class Stack<T> implements Iterable<T> { | |
#arr: Array<T> = [] | |
constructor(arr?: Array<T>) { | |
if (arr) { | |
this.#arr = arr.slice() | |
} | |
} | |
push(el: T): void { | |
this.#arr.push(el) | |
} | |
pop(): T | undefined { | |
return this.#arr.pop() | |
} | |
size(): number { | |
return this.#arr.length | |
} | |
[Symbol.iterator](): Iterator<T> { | |
const privArr = this.#arr | |
this.#arr = [] | |
return new class <T> implements Iterator<T> { | |
constructor(private arr: Array<T>) {} | |
next() { | |
return { | |
done: this.arr.length === 0, | |
value: this.arr.pop() as T | |
} | |
} | |
}(privArr) | |
} | |
} | |
export class Queue<T> implements Iterable<T>{ | |
#startIdx = 0 | |
#endIdx = 0 | |
#m = new Map<number, T>() | |
constructor(arr?: Array<T>) { | |
if (arr) { | |
for (const el of arr) { | |
this.#m.set(this.#endIdx, el) | |
this.#endIdx++ | |
} | |
} | |
} | |
enqueue(el: T): void { | |
this.#m.set(this.#endIdx, el) | |
this.#endIdx++ | |
} | |
dequeue(): T | undefined { | |
const el = this.#m.get(this.#startIdx) | |
this.#m.delete(this.#startIdx) | |
this.#startIdx++ | |
return el | |
} | |
size(): number { | |
return this.#endIdx - this.#startIdx | |
} | |
*[Symbol.iterator](): Iterator<T> { | |
let privStartIdx = this.#startIdx | |
let privEndIdx = this.#endIdx | |
const privM = this.#m | |
this.#startIdx = 0 | |
this.#endIdx = 0 | |
this.#m = new Map<number, T>() | |
while (privEndIdx - privStartIdx >= 0) { | |
const el = privM.get(privStartIdx) as T | |
privM.delete(privStartIdx) | |
privStartIdx++ | |
yield el | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment