Last active
January 13, 2018 23:45
-
-
Save zeusdeux/f5eaf64a42d42705e6c75ed8cda2fa37 to your computer and use it in GitHub Desktop.
Make arrays negative indexable using a Proxy
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
function makeArrayNegativeIndexable(arr) { | |
if (!Array.isArray(arr)) return arr | |
return new Proxy(arr, { | |
get(target, prop) { | |
return target[getIndex(target.length, prop)] | |
}, | |
set(target, prop, val) { | |
let index = getIndex(target.length, prop) | |
target[index] = val | |
return val | |
} | |
}) | |
} | |
function getIndex(arrLen, prop) { | |
// calling parseInt on a symbol throws hence this is first | |
if (typeof prop === 'symbol') return prop | |
let index = Number.parseInt(prop, 10) | |
return !Number.isNaN(index) && index == prop && index < 0 ? arrLen + index : prop | |
} | |
const x = [1, 2] | |
const y = makeArrayNegativeIndexable(x) | |
console.assert(x[0] === y[-2]) | |
console.assert(x[1] === y[-1]) | |
y[2] = 'test' | |
y[-2] = false | |
console.assert(x[2] === y[2]) | |
console.assert(x[1] === y[-2]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment