Created
October 4, 2021 17:08
-
-
Save mshick/6331eed9faf1d085386807183068c0ce to your computer and use it in GitHub Desktop.
python-slice-array
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
| /** | |
| * 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