Created
March 15, 2023 18:03
-
-
Save olegon/b79dc158c75c37a8f200d42f19364e34 to your computer and use it in GitHub Desktop.
This file contains 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
class Node { | |
constructor(value, next) { | |
this.value = value; | |
this.next = next; | |
} | |
} | |
class Stack { | |
constructor() { | |
this.firstNode = null; | |
this.length = 0; | |
} | |
add(value) { | |
const node = new Node(value, this.firstNode) | |
this.firstNode = node; | |
this.length++; | |
return value; | |
} | |
peek() { | |
if (this.firstNode == null) throw new Error('Stack is empty.'); | |
return this.firstNode.value; | |
} | |
pop() { | |
if (this.firstNode == null) throw new Error('Stack is empty.'); | |
const node = this.firstNode; | |
this.firstNode = node.next; | |
this.length--; | |
return node.value; | |
} | |
[Symbol.iterator]() { | |
let node = this.firstNode; | |
return { | |
next() { | |
if (node == null) { | |
return { | |
done: true, | |
value: undefined | |
} | |
} | |
else { | |
const value = node.value; | |
node = node.next; | |
return { | |
done: false, | |
value | |
} | |
} | |
} | |
} | |
} | |
} | |
const size = 10_000_000; | |
const s = new Stack(); | |
for (let i = 0; i < size; i++) { | |
const value = ~~(Math.random() * 100); | |
s.add(value); | |
// console.log(value); | |
} | |
console.log(`Size: ${s.length}`); | |
for (let i = 0; i < size; i++) { | |
const value = s.pop(); | |
// console.log(value); | |
} | |
console.log(`Size: ${s.length}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment