Answer the question
In order to leave comments, you need to log in
How to understand given JavaScript code with loop and shift method?
Task: In a variable called applyAndEmpty, build and store a function that takes in a single number and any Queue of functions as inputs and then applies the Queue's functions in order to the input number, where the results of each function become the next function's input . Additionally, the queue should be empty following your application. + must be executed in a loop, not in the .map() method.
The code :
var puzzlers = [
function ( a ) { return 8*a - 10; },
function ( a ) { return (a-3) * (a-3) * (a-3); },
function ( a ) { return a * a + 4; },
function ( a ) { return a % 5; }
];
var start = 2;
var applyAndEmpty = function( input, queue ) {
var length = queue.length;
for(var i = 0; i<length; i++){
input = queue.shift()(input);
}
return input;
};
alert(applyAndEmpty(start, puzzlers));
Answer the question
In order to leave comments, you need to log in
The shift method returns the removed object. And it turns out that input is the parameters that you pass to the remote-returned method.
And this only affects the final value of the input property.
Roughly speaking, in the return from the first method, 1 was added to input === 0
, then this property, already with the value 1, was passed to the second method, where another one was added to it.
The input property was passed to the third method when it had a value of 2. And so on...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question