Skip to content

Instantly share code, notes, and snippets.

@jordanrios94
Created February 1, 2023 05:37
Show Gist options
  • Save jordanrios94/22e881e5cdee07687b676f1d54254fb3 to your computer and use it in GitHub Desktop.
Save jordanrios94/22e881e5cdee07687b676f1d54254fb3 to your computer and use it in GitHub Desktop.
Coding Exercise - Weave
/*
Implement the 'weave' function.
- Weave receives two queues as arguments and combines the contents of each into a new, third queue
- The third queue should contain the alternating content of the two queues
- The function should handle queues of different lengths without inserting 'undefined' into the new one
- Do not access the array inside of any queue, only use the add, remove, and peek functions
*/
function weave(sourceOne, sourceTwo) {
const newQueue = new Queue();
while (sourceOne.peek() || sourceTwo.peek()) {
if (sourceOne.peek()) {
newQueue.add(sourceOne.remove());
}
if (sourceTwo.peek()) {
newQueue.add(sourceTwo.remove());
}
}
return newQueue;
}
// You should not need to make any changes to this class
class Queue {
constructor() {
this.data = [];
}
add(record) {
this.data.unshift(record);
}
remove() {
return this.data.pop();
}
peek() {
return this.data[this.data.length - 1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment