Skip to content

Instantly share code, notes, and snippets.

@TimothyGu
Created October 8, 2017 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TimothyGu/8f930b931a51999b6100cb42b1156153 to your computer and use it in GitHub Desktop.
Save TimothyGu/8f930b931a51999b6100cb42b1156153 to your computer and use it in GitHub Desktop.
Array with a negative length!
'use strict';
const OriginalArray = global.Array;
global.Array = function Array(...args) {
const arr = new OriginalArray(...args);
let length = arr.length;
return new Proxy(arr, {
set(target, propKey, value, Receiver) {
if (propKey === 'length') {
const cast1 = +value;
const cast2 = value >>> 0;
if (cast1 !== cast2) {
length = cast1;
return true;
}
}
const res = Reflect.set(target, propKey, value, Receiver);
length = target.length;
return res;
},
get(target, propKey, Receiver) {
if (propKey === 'length') {
return length;
}
return Reflect.get(target, propKey, Receiver);
}
});
};
global.Array.isArray = OriginalArray.isArray;
global.Array.prototype = OriginalArray.prototype;
const newArray = new Array();
console.log(Array.isArray(newArray));
// Prints true!
newArray.length = -1;
console.log(newArray.length);
// Prints -1!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment