1

The following question has been asked of me in my studies of javascript:

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.

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.

Here are the following tests I am supposed to run:

nextInLine([], 5) should return a number.   
nextInLine([], 1) should return 1    
nextInLine([2], 1) should return 2    
nextInLine([5,6,7,8,9], 1) should return 5   
After nextInLine(testArr, 10), testArr[4] should be 10

I am basicially supposed to remove the first item in the array and add the item to the end of the array. I am drawing a blank and here is what I have so far:

function nextInLine(arr, item) {

  var temp = [];
  for(var i = 0; i < arr.length; i++){

      if(arr[i] == arr[0]){
          temp = arr[i];
          arr[i] = arr[i+1];
      }
  }

  return item;  
}

// Test 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));

With this example my output is the following:

Before: [1,2,3,4,5]
 6
After: [2,3,3,4,5]

I have also tried it this way:

function nextInLine(arr, item) {
  // Your code here
  arr.push();
  arr.pop(arr[0]);
  return item;  
}


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


console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); 
console.log("After: " + JSON.stringify(testArr));

And get this:

Before: [1,2,3,4,5]
6
After: [1,2,3,4]

If someone can guide me it would be greatly appreciated.

UPDATE

Is there a way to do so without the built in methods?

1
  • I agree that is what threw me off, however, they wanted to see me try it with and without some of the built in methods. Commented Jun 25, 2018 at 18:24

1 Answer 1

3

You can just add the item to the end and then return the first element and remove it. Note that pop removes the last item from an array, the method you want to remove the first is shift:

function nextInLine(arr, item) {
    arr.push(item);
    return arr.shift();
}
Sign up to request clarification or add additional context in comments.

1 Comment

I was looking too much into it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.