Skip to content

Instantly share code, notes, and snippets.

@mshick
Created October 4, 2021 17:08
Show Gist options
  • Select an option

  • Save mshick/6331eed9faf1d085386807183068c0ce to your computer and use it in GitHub Desktop.

Select an option

Save mshick/6331eed9faf1d085386807183068c0ce to your computer and use it in GitHub Desktop.
python-slice-array
/**
* Accomodating the JSONPath array range syntax, this is similar to the Python
* slice function
*/
export function sliceArray<T = unknown>(
arr: T[],
start?: number,
stop?: number,
step = 1
): T[] {
// Start coercion
start = isUndefined(start) || Math.abs(start) === 0 ? 0 : start;
start = isNegativeNumber(start) ? arr.length - Math.abs(start) : start;
// Stop coercion
stop = isUndefined(stop) || Math.abs(stop) === 0 ? arr.length : stop;
stop = isNegativeNumber(stop) ? arr.length - Math.abs(stop) : stop;
// Step coercion - JSONPath compat
step = step === 0 ? 1 : step;
const slicedArray: T[] = [];
// JSONPath doesn't support negative steps, neither do we
if (isNegativeNumber(step)) {
return slicedArray;
}
for (let index = start; index < stop; index += step) {
slicedArray.push(arr[index]);
}
return slicedArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment