Skip to content

Instantly share code, notes, and snippets.

@yashshah1
Last active July 20, 2020 11:03
Show Gist options
  • Save yashshah1/15dec6cf5ff08ce06fd688c3606ec7f8 to your computer and use it in GitHub Desktop.
Save yashshah1/15dec6cf5ff08ce06fd688c3606ec7f8 to your computer and use it in GitHub Desktop.
Negative Indexing in JavaScript Arrays
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