function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
const copy = obj.constructor();
for (const attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
// With the `clone()` function, you can now do the following:
Array.prototype.subarray = function(start, end) {
if (!end) {
end = this.length;
}
const newArray = clone(this);
return newArray.slice(start, end);
};
// Without a copy you will lose your original array.
// **Example:**
const array = [1, 2, 3, 4, 5];
console.log(array.subarray(2)); // print the subarray [3, 4, 5, subarray: function]
console.log(array); // print the original array [1, 2, 3, 4, 5, subarray: function]