Skip to content

Instantly share code, notes, and snippets.

@dSalieri
Last active July 16, 2021 17:55
Show Gist options
  • Save dSalieri/f2c67bfb2eb3b5e90e3c668517f24911 to your computer and use it in GitHub Desktop.
Save dSalieri/f2c67bfb2eb3b5e90e3c668517f24911 to your computer and use it in GitHub Desktop.
less fast than slice, but you have two arrays in one object that may be useful for some operation
function sliceAdvanced(arr, start, end) {
arr = createArrayFromArrayLike(arr);
let boundary1 = start === undefined || arr.length + start < 0 ? 0 : start < 0 ? arr.length + start : start > arr.length ? arr.length : start;
let boundary2 = end === undefined || end > arr.length ? arr.length : end > 0 ? end : arr.length + end < 0 ? 0 : arr.length + end;
let actualLength = boundary2 - boundary1 < 0 ? 0 : boundary2 - boundary1;
let slicedArr = Array(actualLength);
let restArr = Array(arr.length - actualLength);
let key = 0;
let shiftForRest = 0;
while (key < arr.length) {
if (key >= boundary1 && key < boundary2) {
if (arr.hasOwnProperty(key)) {
slicedArr[key - boundary1] = arr[key];
}
} else {
if (key === boundary2) {
shiftForRest = actualLength;
}
if (arr.hasOwnProperty(key)) {
restArr[key - shiftForRest] = arr[key];
}
}
key++;
}
return { sliced: slicedArr, rest: restArr };
function createArrayFromArrayLike(arg) {
if (Array.isArray(arg)) return arg;
arg = Object(arg);
let arr = Array(arg.length ? arg.length : 0);
let i = -1;
while (arg.length > ++i) {
if (arg.hasOwnProperty(i)) arr[i] = arg[i];
}
return arr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment