Skip to content

Instantly share code, notes, and snippets.

@thebearingedge
Last active July 23, 2022 22:16
Show Gist options
  • Save thebearingedge/cbd1412573899a0345a37f3070d936fc to your computer and use it in GitHub Desktop.
Save thebearingedge/cbd1412573899a0345a37f3070d936fc to your computer and use it in GitHub Desktop.
A "real" array in JS. Not really.
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