Skip to content

Instantly share code, notes, and snippets.

@elmpp
Last active March 24, 2020 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elmpp/3a5d22079c82431c54ae04557f96905b to your computer and use it in GitHub Desktop.
Save elmpp/3a5d22079c82431c54ae04557f96905b to your computer and use it in GitHub Desktop.
Next item or first of array
/**
Will find the next/prev element from an array based on given element. Will loop back to first/last if given step value exceeds
the bounds of the items
@remarks
{@link https://tinyurl.com/r3nhday | GH Gist url}
@example
```ts
const val1 = nextRecurse(items, 'b')
const val2 = nextRecurse(items, 'd')
const val3 = nextRecurse(items, 'b', 2)
const val4 = nextRecurse(items, 'b', -2)
const val5 = nextRecurse(items, 'b', -6)
const val6 = nextRecurse(items, 'b', 6)
console.log('val1 :', val1);
console.log('val2 :', val2);
console.log('val3 :', val3);
console.log('val4 :', val4);
console.log('val5 :', val5);
console.log('val6 :', val6);
```
*/
const nextRecurse = <T extends any = string>(items: T[], item: T, step = 1): T => {
const index = items.indexOf(item)
if (index === -1) throw new Error(`Unrecognised item '${item}'`)
let intendedIndex = index + step
if (intendedIndex >= items.length) intendedIndex = intendedIndex % items.length
if (intendedIndex < 0) intendedIndex = items.length + (intendedIndex % items.length)
return items[intendedIndex]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment