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?