Argument Rotator

Medium ImportantCodility

Prompt

In this challenge, you are tasked with creating a function in JavaScript named argumentRotator. This function will accept an arbitrary number of arguments and return a new function that, when invoked, cycles through the provided arguments in the order they were originally passed.

Requirements

  • The argumentRotator function should accept an arbitrary number of arguments.
  • The argumentRotator function should return a new function.
  • The returned function should remember its state between invocations.
  • The returned function should return the next argument in the sequence each time it is called, cycling back to the first argument once it reaches the end.

Playground

Hint 1

Consider using JavaScript's closure feature to remember the function's state between invocations.

Hint 2

The modulus (%) operator can be useful for implementing the cycling behavior.

Solution

Explanation

  • Function Definition: The argumentRotator function is defined using the rest parameter syntax (...args). This syntax allows us to pass an arbitrary number of arguments to the function, which will be collected into an array.

  • State Variable: Inside argumentRotator, a state variable currentValueIndex is defined and initialized to 0. This variable keeps track of the current index of the argument that should be returned.

  • Closure and Returned Function: argumentRotator then returns a new function. This returned function has access to the args array and the currentValueIndex variable due to JavaScript's closure feature. This means that it remembers these values even after the argumentRotator function has finished executing.

  • Accessing the Current Argument: Each time the returned function is called, it accesses the current argument in the args array using the currentValueIndex.

  • Index Incrementation: After accessing the current argument, the function increments the currentValueIndex. If currentValueIndex becomes equal to the length of args (which would be an out-of-bounds index), it is reset back to 0 due to the modulus operation. This operation ensures the cycling behavior, wrapping back to the first argument after reaching the end.

  • Return Value: Finally, the function returns the current argument, as stored in returnValue.

In short, the argumentRotator function utilizes JavaScript's closure feature to remember its state (the current index and the arguments) between invocations, cycling through the arguments each time it is called.

00:00