Last active
August 12, 2016 12:51
-
-
Save deepak/41ffb9925d33ff1f06250aacb3667971 to your computer and use it in GitHub Desktop.
javascript helper to get monotonically increasing values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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