Last active
July 23, 2022 22:16
-
-
Save thebearingedge/cbd1412573899a0345a37f3070d936fc to your computer and use it in GitHub Desktop.
A "real" array in JS. Not really.
This file contains 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
class RealArray extends Array { | |
constructor(length) { | |
if (!Number.isInteger(length) || length < 0) { | |
throw new Error('RealArray requires a positive integer length') | |
} | |
function boundsCheck(index) { | |
if (index in Array.prototype) { | |
throw new RangeError('RealArray does not have ' + index) | |
} | |
if (parseInt(index, 10) !== parseFloat(index, 10)) { | |
throw new RangeError('index must be an integer') | |
} | |
if (index < 0 || index >= length) { | |
throw new RangeError('index out of bounds of RealArray') | |
} | |
} | |
super(length) | |
Object.defineProperty(this, 'length', { | |
value: length, | |
writable: false, | |
configurable: false | |
}) | |
this.__proto__ = new Proxy(this.fill(null), { | |
has() { | |
return false | |
}, | |
getPrototypeOf() { | |
return Array.prototype | |
}, | |
get(array, index) { | |
boundsCheck(index) | |
return array[index] | |
}, | |
set(array, index, value) { | |
boundsCheck(index) | |
return (array[index] = value) | |
}, | |
}) | |
Object.preventExtensions(this) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment