Last active
July 9, 2018 09:00
-
-
Save 7cc/f71f58f43b6656c9afa1f9b45512ec8d to your computer and use it in GitHub Desktop.
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
| // simple iterator | |
| var wm = new WeakMap() | |
| function prev(array) { | |
| var counter = wm.get(array) | |
| if (!counter) { | |
| return undefined | |
| } | |
| counter -= 1 | |
| wm.set(array, counter) | |
| return array[counter] | |
| } | |
| function next(array) { | |
| var counter = wm.get(array) | |
| if (counter === undefined) { | |
| wm.set(array, 0) | |
| return array[0] | |
| } | |
| if (counter > array.length) { | |
| return undefined | |
| } | |
| counter += 1 | |
| wm.set(array, counter) | |
| return array[counter] | |
| } |
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
| var array = [..."abcd"] | |
| next(array) // a | |
| next(array) // b | |
| next(array) // c | |
| prev(array) // b | |
| prev(array) // a | |
| next(array) // b | |
| next(array) // c | |
| next(array) // d | |
| next(array) // undefined | |
| prev(array) // d |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment