-3

sequence( start, step )

This function takes two numeric inputs, start and stop, and returns a function of no inputs. The resulting function will generate a sequence of values beginning with start and offset by step Each function call will generate the next value in the sequence. Examples

var x = sequence( 3, 15 );
[ x(), x(), x() ] => [ 3, 18, 33 ]
var y = sequence( 28, -5 );
[ y(), y(), y() ] => [ 28, 23, 18 ]

How do I go about solving this?

  • This is a hint, calling sequence returns a function, this function needs its own scope. Going further would be spoiling. – axelduch Nov 17 '16 at 16:21
  • 3
    If you don't give it any attempt, we're just solving the problem for you. If you show what you have tried, along with error messages and the actual vs. expected behavior, we can pinpoint what you were doing wrong and you will have learned a lot more. – Ruan Mendes Nov 17 '16 at 16:24

1 Answers1

1

sequence doesn't simply return a function. It returns a function with a closure that keeps track of the start/step values. So start, step, and counter are bound to it. So you can work with them.

function sequence(start, step) {
  var counter = -1;
  return function() {
    // This is the function that will return the next element
    // It uses the counter, start, step variables from its closure
    // Notice they live outside of the inner function so the counter is not reset
    // every time you run this function.
    counter++;
    return start + step * counter;
  };
};

var x = sequence(1, 3);
var y = sequence(-1, -2);

console.log('x()', x(), x(), x());
console.log('y()', y(), y(), y());
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151