Skip to content

Instantly share code, notes, and snippets.

@mhdSid
Last active November 11, 2018 22:33
Show Gist options
  • Save mhdSid/5ded50e755192898cbea028db94be421 to your computer and use it in GitHub Desktop.
Save mhdSid/5ded50e755192898cbea028db94be421 to your computer and use it in GitHub Desktop.
Simple & Generic Way to Iterate Backwards & Forwards through an Array
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