Last active
September 25, 2015 09:38
-
-
Save OnesimusUnbound/901648 to your computer and use it in GitHub Desktop.
Generator mixin's for underscore.js
This file contains 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
/** | |
* counter | |
* ======= | |
* Creates counter that will generate number, starting from `start` (default to 0) | |
* incrementing (or decrementing) by `step` (default to 1). Based on | |
* [Python's itertools.count](http://docs.python.org/library/itertools.html#itertools.count). | |
* | |
* cycle | |
* ===== | |
* Returns a function that will generate items in `iterable` for each call, | |
* starting with the first one. Once the entire `iterable` has been returned, | |
* the cycle will return to the first item in `iterable` and repeat the cycle. | |
* Based on [Python's itertools.cycle](http://docs.python.org/library/itertools.html#itertools.cycle). | |
* | |
* enumerate | |
* ========= | |
* Accepts array `arr` and an optional `startsAt` (defaults to 0) and returns | |
* an array whose items in `arr` have a corresponding index | |
* Based on [Python's builtin function enumerate](http://docs.python.org/2/library/functions.html#enumerate) | |
*/ | |
_.mixin({ | |
counter: function(start, step) { | |
start = start || 0; | |
step = step || 1; | |
var countNumber = start - step; | |
return function() { | |
return (countNumber += step); | |
}; | |
}, | |
cycle: function(iterable) { | |
iterable = _.isString(iterable) ? iterable.split('') : _.toArray(iterable); | |
var size = iterable.length; | |
if (!size) | |
throw new TypeError('object should be iterable and should not be empty'); | |
var idx = 0; | |
return function() { | |
if(idx >= size) idx = 0; | |
return iterable[idx++]; | |
}; | |
}, | |
enumerate: function(arr, startAt) { | |
startAt = (!startAt) ? 0 : startAt; | |
var indexes = _.range(startAt, arr.length + startAt); | |
return _.zip(indexes, arr); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment