Skip to content

Instantly share code, notes, and snippets.

@ishwarrimal
Created May 21, 2020 10:01
Show Gist options
  • Save ishwarrimal/5921a1443034bcc1b634e97cb920a882 to your computer and use it in GitHub Desktop.
Save ishwarrimal/5921a1443034bcc1b634e97cb920a882 to your computer and use it in GitHub Desktop.
Implementation of Queue in JS
function Queue() {
this.length = 0;
}
Queue.prototype.push = function (item) {
var node = {item: item};
if (this.last) {
this.last = this.last.next = node;
} else {
this.last = this.first = node;
}
this.length++;
};
Queue.prototype.shift = function () {
var node = this.first;
if (node) {
this.first = node.next;
if (!(--this.length)) {
this.last = undefined;
}
return node.item;
}
};
Queue.prototype.slice = function (start, end) {
start = typeof start === 'undefined' ? 0 : start;
end = typeof end === 'undefined' ? Infinity : end;
var output = [];
var i = 0;
for (var node = this.first; node; node = node.next) {
if (--end < 0) {
break;
} else if (++i > start) {
output.push(node.item);
}
}
return output;
}
module.exports = Queue;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment