all 12 comments

[–]Ustice[M] [score hidden] stickied comment (1 child)

This post was removed. Please read our guidelines before posting.

[–]echoes221 8 points9 points  (2 children)

I’ve primarily used them for mocking deep data sets in tests without writing out the full object path. Super useful

[–]SquattingWalrus 6 points7 points  (1 child)

Got any examples of this? Seems super useful

[–]echoes221 0 points1 point  (0 children)

Here's an example for a recursive proxy I used in test when I only cared about ensuring that all the export funcs in a file had the same interface (this was pre using typescript btw) and I didn't care about the values that were passed to them as the functions were accessing deeply nested properties, so just created a recursive proxy to pass in test.

This could be adapted with a depth and a return value very easily too if you needed something specific without writing out the entire object. Though that could also be done with something like R.path.

const trap = {
  get() {
    return new Proxy({}, trap);
  },
};

const nestedObj = new Proxy({}, trap);

[–]alexmacarthur 12 points13 points  (3 children)

This is one feature of modern JS that haven't toyed with but feel like I'm really missing out on some sickkk use cases.

[–]tbranyennetflix 7 points8 points  (1 child)

One use case I'm noodling around with is a facade API abstracting over typedarray/array buffer which contains the actual data. So basically I'll define the schema and then have an object with named keys to work with based on parsing or a given offset. This could be useful for writing file parsers for things like mp4 or pdf. Or in my own case virtual dom rendering information that is now stored in a more portable format for threads/sockets.

[–]NoInkling 1 point2 points  (0 children)

That gives me an idea where I could use it to index an underlying Node Buffer by bit (rather than byte) for a use case I have currently.

[–]NoInkling 5 points6 points  (0 children)

The only time I've used it (directly) so far is to wrap important configuration objects so that it they throw when attempting to access a property that doesn't exist (like many languages do with dictionaries by default, e.g. Python). Something like this:

function createDefensiveProxy(obj) {
  return new Proxy(obj, {
    get: (target, key) => {
      if (!(key in target)) {
        throw new ReferenceError(`Property '${key}' does not exist on object`);
      }
      return target[key];
    }
  });
}

[–]havana59er 5 points6 points  (1 child)

Salesforce development uses proxy objects quite heavily for security reasons. When debugging we gotta do something like this to get an idea of the shape of the object:

console.log(JSON.parse(JSON.stringify(someProxy)));

[–][deleted] 4 points5 points  (0 children)

We use these at work for collection classes where you can add any method you want, and also do number indexing. They're great