Last active
February 23, 2024 01:35
-
-
Save micaiah-effiong/ea4c1d435cc3a52403aad1b3c47db69a to your computer and use it in GitHub Desktop.
get a fixed range of data from an array. if bounds overflow it shift in the other direction.
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
| function edgeAwareSlice<T>(arr: Array<T>, start: number, win: number) { | |
| if(win > arr.length) { return arr } | |
| const half = Math.floor(win/2) | |
| let front = start - half | |
| let back = start + half; | |
| if (back >= arr.length){ | |
| // console.log('gap', {front, back, diff: (back+win%2) - arr.length}, arr.length) | |
| front -= (back+win%2) - arr.length | |
| back = arr.length | |
| } | |
| if (front <= 0){ | |
| let fronthalf = start -front | |
| let frontrem = fronthalf - half | |
| back += Math.abs(front) | |
| front = frontrem | |
| } | |
| // console.log({front,back, half, start}) | |
| return arr.slice(front,back+win%2) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The function's purpose is to extract a window of elements from the given array, handling edge cases where the window goes beyond the beginning or end of the array.