Created
November 3, 2021 23:50
-
-
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)
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
| 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