Skip to content

Instantly share code, notes, and snippets.

@heatherbooker
Created November 18, 2016 19:19
Show Gist options
  • Save heatherbooker/fcb76ebed884e0dea8082df9541f0c79 to your computer and use it in GitHub Desktop.
Save heatherbooker/fcb76ebed884e0dea8082df9541f0c79 to your computer and use it in GitHub Desktop.
function Queue(originalQueue) {
let queue = originalQueue || [];
function removeElement(q, i) {
const index = i === 'last' ? q.length - 1 : i;
if (!q[index + 1]) {
q[index] = undefined;
q.length = q.length - 1;
}
}
return {
enqueue (element) {
for (let i = 0; i < queue.length + 1; i++) {
if (!queue[i]) {
queue[i] = element;
return;
}
}
},
dequeue () {
for (let i = 1; i < queue.length + 1; i++) {
// Moves every element forward (towards index 0) by 1.
queue[i - 1] = queue[i];
removeElement(queue, i);
}
},
buttIn (element) {
for (let i = queue.length; i >= 0; i--) {
queue[i] = queue[i - 1];
}
queue[0] = element;
},
giveUp () {
removeElement(queue, 'last');
},
peek () {
return queue[0];
},
isEmpty() {
return !queue.length;
},
_view () {
return queue;
}
};
}
function test(q, a) {
let aQueue = new Queue(q);
console.log('initial array:', aQueue._view());
aQueue.enqueue('x');
aQueue.dequeue();
console.log('dequeued', aQueue._view());
aQueue.enqueue('z');
aQueue.enqueue('q');
aQueue.buttIn('t');
aQueue.giveUp();
aQueue.enqueue('a');
aQueue.buttIn('e');
console.log('should be:', a);
console.log('is:', aQueue._view());
console.log('');
}
let q = ['a','s','d','f','g'];
let a = '[e, t, s, d, f, g, x, z, a]';
test(q, a);
test(null, '[e, t, z, a]');
test(['g'], '[e, t, x, z, a]');
q = new Queue();
q.buttIn('x');
console.log(q.isEmpty());
console.log(q._view());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment