Published on

Weaving Two Queues Together - JavaScript Data Structures

551 words3 min read
Authors
  • avatar
    Name
    Curtis Warcup
    Twitter

Directions:

  1. Implement a peek() method in this Queue class. Peek should return the last element (the next one to be returned) from the queue without removing it.
  2. Implement the weave(q1, q2) function.
    • Weave receives two queues as arguments and combines the contents of each into 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 enqueue, dequeue, and peek functions.

Example:

const queueOne = new Queue()
queueOne.enqueue(1)
queueOne.enqueue(2)
const queueTwo = new Queue()
queueTwo.enqueue('Hi')
queueTwo.enqueue('There')

const q = weave(queueOne, queueTwo)
q.dequeue() // 1
q.dequeue() // 'Hi'
q.dequeue() // 2
q.dequeue() // 'There'

Weave Solution

class Queue {
  constructor() {
    this.data = []
  }

  enqueue(item) {
    this.data.push(item)
  }

  dequeue(item) {
    return this.data.shift()
  }

  peek(item) {
    return this.data[0]
  }

  isEmpty() {
    return this.data.length === 0
  }
}

function weave(sourceOne, sourceTwo) {
  const q = new Queue()

  // as long as our next element is NOT undefined...
  while (sourceOne.peek() || sourceTwo.peek()) {
    if (sourceOne.peek()) {
      q.enqueue(sourceOne.dequeue())
    }
    if (sourceTwo.peek()) {
      q.enqueue(sourceTwo.dequeue())
    }
  }
  return q
}
  • Create a new Queue object with new Queue().
  • Iterate through each input queue, dequeueing each element and adding it to the new queue. This will shorten the input queues.
  • If one queue is empty, add the remaining elements from the other queue to the new queue.