Skip to content

Instantly share code, notes, and snippets.

@MananTank
Created September 8, 2020 16:39
Show Gist options
  • Save MananTank/d0d6dea2c97d6d65ebe3a3111134998d to your computer and use it in GitHub Desktop.
Save MananTank/d0d6dea2c97d6d65ebe3a3111134998d to your computer and use it in GitHub Desktop.
create arrays with super powers, with negative indexing and range support.
// code to create arrays with super powers !
const superArray = (initArray) => {
const toPos = (index, target) => {
const _index = Number(index);
return index < 0 ? target.length + _index : _index;
};
return new Proxy(initArray, {
get(target, prop) {
const rangeSplit = prop.split(":");
if (rangeSplit.length > 1) {
let [from, to] = rangeSplit;
from = toPos(from, target);
to = toPos(to, target);
return target.filter((a, i) => i <= to && i >= from);
} else return Reflect.get(target, toPos(prop, target));
}
});
};
// usage example :
// create a super array
const arr = superArray([10, 20, 30, 40, 50, 60, 70]);
// use it like a normal array, but with extra features!
console.log(arr[-1]); // 70
console.log(arr["1:3"]); // [20, 30, 40]
console.log(arr["3:-1"]); // [40, 50, 60, 70]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment