Created
March 6, 2018 14:58
-
-
Save adambene/bc5de9acaf60d4521ac32e7564d6c208 to your computer and use it in GitHub Desktop.
Iterate through an array in an alternating fashion in JavaScript
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
| class AlternatingArray extends Array { | |
| constructor(...args) { | |
| super(...args); | |
| } | |
| *[Symbol.iterator](){ | |
| for (let i = 0; i < this.length; i += 2) { | |
| yield this[i]; | |
| } | |
| for (let i = 1; i < this.length; i += 2) { | |
| yield this[i]; | |
| } | |
| } | |
| } | |
| const a = new AlternatingArray(1, 2, 3, 4, 5, 6, 7, 8); | |
| console.log([...a]); // [1, 3, 5, 7, 2, 4, 6, 8] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment