freeCodeCamp/curriculum/challenges/english/02-javascript-algorithms-an.../basic-javascript/stand-in-line.english.md

2.7 KiB

id title challengeType videoUrl
56533eb9ac21ba0edf2244c6 Stand in Line 1 https://scrimba.com/c/ca8Q8tP

Description

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.

Instructions

Tests

tests:
  - text: <code>nextInLine([], 5)</code> should return a number.
    testString: assert.isNumber(nextInLine([],5));
  - text: <code>nextInLine([], 1)</code> should return <code>1</code>
    testString: assert(nextInLine([],1) === 1);
  - text: <code>nextInLine([2], 1)</code> should return <code>2</code>
    testString: assert(nextInLine([2],1) === 2);
  - text: <code>nextInLine([5,6,7,8,9], 1)</code> should return <code>5</code>
    testString: assert(nextInLine([5,6,7,8,9],1) === 5);
  - text: After <code>nextInLine(testArr, 10)</code>, <code>testArr[4]</code> should be <code>10</code>
    testString: nextInLine(testArr, 10); assert(testArr[4] === 10);

Challenge Seed

function nextInLine(arr, item) {
  // Your code here

  return item;  // Change this line
}

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

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));

Before Test

var logOutput = [];
var originalConsole = console
function capture() {
    var nativeLog = console.log;
    console.log = function (message) {
        logOutput.push(message);
        if(nativeLog.apply) {
          nativeLog.apply(originalConsole, arguments);
        } else {
          var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');
          nativeLog(nativeMsg);
        }
    };
}

function uncapture() {
  console.log = originalConsole.log;
}

capture();

After Test

uncapture();
testArr = [1,2,3,4,5];
(function() { return logOutput.join("\n");})();

Solution

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

function nextInLine(arr, item) {
    arr.push(item);
    return arr.shift();
}