DEV Community

Samuel Rouse
Samuel Rouse

Posted on

Chaos Proxy: JavaScript Shenanigans

JavaScript Proxies can do almost anything. To demonstrate, let's set up a simple proxy that will sometimes return incorrect values for a proxied function.

Requirements

  • Accepts a target function
  • Accepts odds of the error (as a fraction of 1)
  • Accepts alternative function to execute instead of the normal response.

The Code

Nothing special here. We're just using the apply trap for functions.

const chaosProxy = (source, odds, alternative) => new Proxy(source, {
  apply(target, context, args) {
    return Math.random() - odds >= 0
      ? alternative.apply(context, args)
      : target.apply(context, args);
  }
});
Enter fullscreen mode Exit fullscreen mode

This basic implementation doesn't have much to it. Simple odds calculation, and you execute one function or the other.

Trying It

const circleArea = (radius) => Math.PI * radius ** 2;
const circleAreaClose = (radius) => 3.14 * radius ** 2;

const roughArea = chaosProxy(circleArea, 0.5, circleAreaClose);

roughArea(2); // 12.566370614359172
roughArea(2); // 12.56
roughArea(2); // 12.56
roughArea(2); // 12.56
roughArea(2); // 12.566370614359172
Enter fullscreen mode Exit fullscreen mode

Variations

I'm not going to build these; I leave them as exercises for the reader. Maybe one of these will speak to you and you'll try solving it.

  • Supporting multiple alternatives with different weights/probabilities.
  • Support manipulating async/promise values.
  • Modify arguments objects to see if mutations cause problems in your app.
  • Return a consistent sequence of responses rather than random ones.
  • Introduce random delays in asynchronous responses rather than changes.

Conclusion

Sure, there are other ways to go about this, but awareness of different parts of JavaScript can come in handy one day. Don't forget to spend a little time trying things. It can sharpen your skills, broaden your perspective, and help you solve real problems in the future.

Top comments (0)