Skip to content

Instantly share code, notes, and snippets.

@MananTank
Created September 8, 2020 16:39
Show Gist options
  • Select an option

  • Save MananTank/d0d6dea2c97d6d65ebe3a3111134998d to your computer and use it in GitHub Desktop.

Select an option

Save MananTank/d0d6dea2c97d6d65ebe3a3111134998d to your computer and use it in GitHub Desktop.

Revisions

  1. MananTank created this gist Sep 8, 2020.
    31 changes: 31 additions & 0 deletions superArray.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    // 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]