Javascript sequences with an array of function calls -


sequence( start, step )

this function takes 2 numeric inputs, start , stop, , returns function of no inputs. resulting function generate sequence of values beginning start , offset step each function call generate next value in 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 go solving this?

sequence doesn't return function. returns function closure keeps track of start/step values. start, step, , counter bound it. can work them.

function sequence(start, step) {    var counter = -1;    return function() {      // function return next element      // uses counter, start, step variables closure      // notice live outside of inner function counter not reset      // every time run 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());


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -