Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaScript Interview Question: Queue
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Solve some arbitrary problem using a queue.
* The interviewer has asked to provide a solution to a problem
* using a Queue as the data structure. Using the native Array
* in JavaScript with restricted access to its full list of methods
* is one possible solution.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
//Queues implement the FIFO method. First in, first out.
class Queue {
constructor() {
this.queue = [];
}
add(record) {
// Use Array#unshift to add record at the beginning of the array.
this.queue.unshift(record);
}
remove() {
//Remove and return the last element in the array.
return this.queue.pop();
}
}
//Test it.
(() => {
let queue = new Queue();
queue.add(1);
queue.add(2);
queue.add(3);
let result = queue.remove();
console.log(result);
})();
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Weave, or merge the results of two queues together into a
* single queue.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
class Queue {
constructor() {
this.queue = [];
}
add(record) {
this.queue.unshift(record);
}
remove() {
return this.queue.pop();
}
peek() {
return this.queue[this.queue.length - 1];
}
}
// Test it.
(() => {
let q1 = new Queue();
let q2 = new Queue();
// Populate Queue 1
'1975'.split('').map(n => q1.add(parseInt(n)));
// Populate Q2
'The Year of the Hare'.split(' ').forEach(word => q2.add(word));
// Merge the two queues together, but alternate between the two queues as they are added.
function weave(source1, source2) {
let queue = new Queue();
while (q1.peek() || q2.peek()) {
if (q1.peek()) {
queue.add(q1.remove());
}
if (q2.peek()) {
queue.add(q2.remove());
}
}
return queue;
}
let combinedQueue = weave(q1, q2);
console.log('Combined Queue', combinedQueue);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment