Skip to content

Instantly share code, notes, and snippets.

@deepak
Last active August 12, 2016 12:51
Show Gist options
  • Save deepak/41ffb9925d33ff1f06250aacb3667971 to your computer and use it in GitHub Desktop.
Save deepak/41ffb9925d33ff1f06250aacb3667971 to your computer and use it in GitHub Desktop.
javascript helper to get monotonically increasing values
const helpers = {
*monotonicallyIncreasingGen(start, step) {
var counter = start;
while (true) {
yield counter;
counter += step;
}
},
monotonicallyIncreasingFunc(start, step) {
var counter = start - step;
return function() {
counter += step;
return counter;
};
}
};
// using ES6 generators
gen = helpers.monotonicallyIncreasingGen(2000, 3000);
console.log(gen.next().value);
console.log(gen.next().value);
// using a closure
next = helpers.monotonicallyIncreasingFunc(2000, 3000);
console.log(next());
console.log(next());
// not happy with this code
const monotonicallyIncreasingCounter = function() {
var counter = 0,
step = 1;
const that = this;;
return {
initializeCounter(start, step=1) {
counter = start - step;
that.step = step;
},
next(step=1) {
counter += step;
return counter;
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment