Created
January 23, 2019 13:47
-
-
Save bflannery/3db5358ddf03aa52605eba275e37a515 to your computer and use it in GitHub Desktop.
JS Stack
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
const _items = new WeakMap() | |
class Stack { | |
constructor(value) { | |
_items.set(this, []); | |
} | |
push(value) { | |
_items.get(this).push(value); | |
} | |
pop() { | |
const items = _items.get(this) | |
if (items.length === 0 ) { | |
throw new Error('Stack is empty.'); | |
} | |
items.pop(); | |
} | |
peek() { | |
const items = _items.get(this) | |
if (items.length === 0 ) { | |
throw new Error('Stack is empty.'); | |
} | |
return items[items.length - 1] | |
} | |
get count() { | |
return _items.get(this).length | |
} | |
} | |
const stack = new Stack(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment