Last active
March 5, 2018 08:55
-
-
Save mayashavin/8b4e31b03d9e3a8a034dd6e40d265cb4 to your computer and use it in GitHub Desktop.
Data Structures - Queue Implementation in JS
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
function Queue(){ | |
var storage = {}, | |
head = 0, | |
tail= 0; | |
return { | |
enQueue: function(item){ | |
storage[tail] = item; | |
tail++; | |
}, | |
deQueue: function(){ | |
var size = tail - head; | |
if (size <= 0) return undefined; | |
var item = storage[head]; | |
delete storage[head]; | |
head++; | |
//Reset the counter | |
if (head === tail){ | |
head = 0; | |
tail = 0; | |
} | |
return item; | |
}, | |
size: function(){ | |
return tail - head; | |
}, | |
peek: function(){ | |
return storage[tail - 1]; | |
}, | |
print: function(){ | |
var result = []; | |
for (var key in storage){ | |
result.push(storage[key]); | |
} | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment