Skip to content

Instantly share code, notes, and snippets.

@dSalieri
Last active July 16, 2021 17:58
Show Gist options
  • Save dSalieri/4b6cd55e5d7b525146dd969816ab2d21 to your computer and use it in GitHub Desktop.
Save dSalieri/4b6cd55e5d7b525146dd969816ab2d21 to your computer and use it in GitHub Desktop.
Slice method that one may be able return reverse result
function slice(arr) {
arr = createArrayFromArrayLike(arr);
return function (start, end, flag) {
let boundary1 = typeof start === "boolean" || start === undefined || arr.length + start < 0 ? 0 : start < 0 ? arr.length + start : start > arr.length ? arr.length : start;
let boundary2 = typeof end === "boolean" || end === undefined || end > arr.length ? arr.length : end > 0 ? end : arr.length + end < 0 ? 0 : arr.length + end;
let inverseFlag = typeof start === "boolean" ? start : typeof end === "boolean" ? end : flag;
let shift = boundary2 - boundary1;
if (inverseFlag) {
let slicedArr = Array(arr.length - shift);
let key = 0;
while (key < arr.length) {
if (key < boundary1) {
if (arr.hasOwnProperty(key)) slicedArr[key] = arr[key];
} else if (key >= boundary2) {
if (arr.hasOwnProperty(key)) slicedArr[key - shift] = arr[key];
} else {
key = boundary2;
continue;
}
key++;
}
return slicedArr;
} else {
let slicedArr = Array(shift);
let key = boundary1;
while (key >= boundary1 && key < boundary2) {
if (arr.hasOwnProperty(key)) slicedArr[key - boundary1] = arr[key];
key++;
}
return slicedArr;
}
};
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;
}
}
/// You can simple invoke by next way
let sliceArr = slice(["a", "b", "c", "d", "e"]);
sliceArr(1, 3); /// ["b","c"];
sliceArr(1, 3, true); /// ["a","d","e"]
/// By the way, negative values also works
sliceArr(1, -1); /// ["b","c","d"]
sliceArr(1, -1, true); /// ["a","e"]
/// Also works single digits
sliceArr(3); /// ["d","e"]
sliceArr(3, true); /// ["a","b","c"]
sliceArr(-3); /// ["c","d","e"]
sliceArr(-3, true); /// ["a","b"]
/// Or at all without args, means digits
sliceArr(); /// ["a","b","c","d","e"]
sliceArr(true); /// []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment