Skip to content

Instantly share code, notes, and snippets.

@micaiah-effiong
Last active February 23, 2024 01:35
Show Gist options
  • Select an option

  • Save micaiah-effiong/ea4c1d435cc3a52403aad1b3c47db69a to your computer and use it in GitHub Desktop.

Select an option

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.
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)
}
@micaiah-effiong
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment