Last active
July 27, 2018 15:21
-
-
Save anish000kumar/0fd37acc866a9577cf259980500b1bbe to your computer and use it in GitHub Desktop.
Stack implementation in javascript (es6)
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
let Stack = (()=>{ | |
let map = new WeakMap(); | |
let _items = []; | |
class Stack { | |
constructor(...items){ | |
// let's store our items array inside the weakmap | |
map.set(this, []); | |
// let's get the items array from map, and store it in _items for easy access elsewhere | |
_items = map.get(this); | |
//if constructor receives any items, it should be stacked up | |
if(items.length>0) | |
items.forEach(item => _items.push(item) ) | |
} | |
push(...items){ | |
//push item to the stack | |
items.forEach(item => _items.push(item) ) | |
return this; | |
} | |
pop(count=0){ | |
//pull out the topmost item (last item) from stack | |
if(count===0) | |
_items.pop() | |
else | |
_items.splice( -count, count ) | |
return this | |
} | |
peek(){ | |
// see what's the last item in stack | |
return _items[_items.length-1] | |
} | |
size(){ | |
//no. of items in stack | |
return _items.length | |
} | |
isEmpty(){ | |
// return whether the stack is empty or not | |
return _items.length==0 | |
} | |
toArray(){ | |
// return items of the queue | |
return _items | |
} | |
} | |
return Stack; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment