Last active
July 20, 2020 11:03
-
-
Save yashshah1/15dec6cf5ff08ce06fd688c3606ec7f8 to your computer and use it in GitHub Desktop.
Negative Indexing in JavaScript Arrays
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
const assert = require('assert'); | |
const applyNegativeIndex = (array) => { | |
assert(Array.isArray(array)); | |
const negativeIndexProxy = new Proxy(array, { | |
get(target, prop) { | |
if (!isNaN(prop)) prop = parseInt(prop); | |
if (prop < 0) prop += target.length; | |
return Reflect.get(target, prop); | |
}, | |
set(target, prop, value) { | |
if (!isNaN(prop)) prop = parseInt(prop); | |
if (prop < 0) prop += target.length; | |
Reflect.set(target, prop, value); | |
} | |
}); | |
return negativeIndexProxy; | |
}; | |
// USAGE: | |
const a = applyNegativeIndex([1, 2, 3, 4]); | |
console.log(a[-1], a[-2]); // 4 3 | |
a[-1] = 100; | |
a[0] = 200; | |
console.log(a); // [200, 2, 3, 100] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment