Last active
November 11, 2018 22:33
-
-
Save mhdSid/5ded50e755192898cbea028db94be421 to your computer and use it in GitHub Desktop.
Simple & Generic Way to Iterate Backwards & Forwards through an Array
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
public iterateBackwards (arrayLength: number, index: number): number { | |
return index = (index <= 0) ? arrayLength - 1 : --index, index; | |
} | |
public iterateForwards (arrayLength: number, index: number): number { | |
return index = (index >= arrayLength - 1) ? 0 : ++index, index; | |
} | |
/* | |
* Usage | |
*/ | |
const myArray: Array<any> = ['1','2','3','4']; | |
const length: number = myArray.length; | |
let index: number = 0; | |
index = iterateBackwards(length, index); //prints 3 | |
index = iterateBackwards(length, index); //prints 2 | |
index = iterateBackwards(length, index); //prints 1 | |
index = iterateBackwards(length, index); //prints 0 | |
index = iterateForwards(length, index); //prints 1 | |
index = iterateForwards(length, index); //prints 2 | |
index = iterateForwards(length, index); //prints 3 | |
index = iterateForwards(length, index); //prints 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment