DEV Community

Randy Rivera
Randy Rivera

Posted on • Updated on

Let's Challenge You.

  • Let's begin by giving you a problem to solve.

In Computer Science a queue is an abstract Data Structure where items are kept in order. New items can be added at the back of the queue and old items are taken off from the front of the queue.

  • Write a function nextInLine which takes an array (arr) and a number (item) as arguments.

  • Then Add the number to the end of the array, then remove the first element of the array.

  • The nextInLine function should then return the element that was removed.
    The function is written out for you here.

function nextInLine(arr, item) {
  // Only change code below this line


  return item;
  // Only change code above this line
}

// Setup
var testArr = [1,2,3,4,5];

// Display code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6));
console.log("After: " + JSON.stringify(testArr));
Enter fullscreen mode Exit fullscreen mode
  • Don't worry about the last bit of code in the console.log, you will learn as you go and I will be here to see it through.

  • Here below, you will find the answer.

function nextInLine(arr, item) {
  // Only change code below this line
  var newArray = arr.push(item);
  var someArray = arr.shift();
  return someArray;
  // Only change code above this line

}

// Setup
var testArr = [1,2,3,4,5];

// Display code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6));
console.log("After: " + JSON.stringify(testArr));
Enter fullscreen mode Exit fullscreen mode
console will display 
Before: [1,2,3,4,5]
After: [2,3,4,5,6]
someArray will equal 1 (returned element that was removed)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)