DEV Community

Discussion on: What is the use of Proxy and Reflect in JavaScript?

Collapse
 
shuckster profile image
Conan

I posted this elsewhere, but here's an example use-case:

Let's say you want to use arrays as accessors, like this:

const array = "the five boxing wizards jump quickly".split(" ");
const words = fancy(array);

words[[3, -1, -2]];
// ["wizards", "quickly", "jump"]

words[-1] = "swiftly";
// ["the", "five", "boxing", "wizards", "jump", "swiftly"]

words[[0, -1]] = ["alpha", "omega"];
// ["alpha", "five", "boxing", "wizards", "jump", "omega"]
Enter fullscreen mode Exit fullscreen mode

You can use Proxy and Reflect to achieve it:

const parseIndexesString = (indexes, maxIndex) =>
  indexes
    .split(",")
    .map((x) => x.trim())
    .map((x) => (/^-\d+$/.test(x) ? maxIndex + +x : x));

const fancyArrayAccessors = {
  get(obj, prop) {
    if (/^\d+$/.test(prop)) {
      return Reflect.get(...arguments);
    }
    const props = parseIndexesString(prop, obj.length);
    return props.map((prop) => obj[prop]);
  },
  set(obj, prop, value) {
    if (/^\d+$/.test(prop)) {
      return Reflect.get(...arguments);
    }
    const props = parseIndexesString(prop, obj.length);
    return props.map((prop, idx) => 
      (obj[prop] = Array.isArray(value) ? value[idx] : value)
    );
  }
};

const fancy = (arr) => new Proxy(arr, fancyArrayAccessors);
Enter fullscreen mode Exit fullscreen mode

Here, Reflect is being used to take care of the "default" case of accessing an array using a normal numerical index.

The rest of the time we're abusing the fact that any key in arr[key] form gets coerced into a string, so can be parsed into whatever we like once it reaches the getter/setter in a Proxy handler.

Collapse
 
rajeshroyal profile image
Rajesh Royal

this looks very helpful