Skip to content

Instantly share code, notes, and snippets.

@signalwerk
Created November 3, 2021 23:50
Show Gist options
  • Select an option

  • Save signalwerk/0dccd31415da9e4edb3f41ec5f75690b to your computer and use it in GitHub Desktop.

Select an option

Save signalwerk/0dccd31415da9e4edb3f41ec5f75690b to your computer and use it in GitHub Desktop.
get an element from an array at a specific position (index) – the index can be negative and exceed the length of the array (Modulo wrapping)
const at = (arr, n) => {
const offset = Math.abs(n) % arr.length;
if (n >= 0) {
return arr[n % arr.length];
} else {
return arr[(arr.length - offset) % arr.length];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment