Checkpoint: Stand In Line
About queues
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.
Instructions
Write a function queue which takes an "array" and an "item" as arguments.
Add the item onto the end of the array, then remove the first element of the array.
The queue function should return the element that was removed.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Useful Links
- Challenge: Manipulate Arrays With push()
- Challenge: Manipulate Arrays With shift()
- Challenge: Passing Values to Functions with Arguments
Problem Explanation:
- Change the code below
//Your Code here
and up to//Change this line
- Take note that you are editing the inside of the queue function
- Use an array function you learned to add the
item
to the end of the arrayarr
- Use an array function you learned to remove the first element from array
arr
- Return the element removed
Hint: 1
push
adds an item to the end of an array.
Hint: 2
shift
removes the first element of an array. It also gives that element back to you.
Hint: 3
- The function queue uses
arr
anditem
. Those are what the tests will use to pass the arrays and elements they will test with and allows the function to be reusable. Do not hardcode any of the tests inside the function.
Spoiler Alert!
Solution ahead!
Code Solution:
function queue(arr, item) {
// Your code here
arr.push(item);
var removed = arr.shift();
return removed; // Change this line
}
Code Explanation:
- Pushes item at the end of arr
- Calls shift on arr to get the first item and stores it in removed
- Returns removed
Example Run
- Test
queue([2], 1);
runs - The
queue
function is called.arr
becomes [2].item
becomes 1. arr.push(item);
Pushes 1 to [2]. Soarr
is now [2,1]var removed = arr.shift();
Removes the first element. Soarr
is now [1]. 2 has been removed and is stored inremoved
return removed;
2 is returned
Note You don't actually need to store it in a variable if you return it directly!
function queue(arr, item) {
// Your code here
arr.push(item);
return arr.shift(); // Change this line
}
Credits:
If you found this page useful, you can give thanks by copying and pasting this on the main chat: thanks @CaroleAnneHannon for your help with Checkpoint: Stand in Line
NOTE: Please add your username only if you have added any relevant main contents to the wiki page. (Please don't remove any existing usernames.)