I
I
Itvanya2014-08-24 20:12:03
JavaScript
Itvanya, 2014-08-24 20:12:03

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

What is not clear : I do not understand the moment when we assign queue.shift () (input); to the input argument; - what is the meaning of this action? Why is there (input) in parentheses after queue.shift() , and how does this affect the process?
Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vasIvas, 2014-08-24
@Itvanya

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 question

Ask a Question

731 491 924 answers to any question