Chaos Proxy: JavaScript Shenanigans

Published: (December 27, 2025 at 03:34 PM EST)
2 min read
Source: Dev.to

Source: Dev.to

Chaos Proxy Overview

JavaScript Proxy objects can intercept and redefine fundamental operations. This example demonstrates a simple proxy that randomly returns either the original function’s result or an alternative result, based on a configurable error probability.

Implementation

const chaosProxy = (source, odds, alternative) => new Proxy(source, {
  apply(target, context, args) {
    // Return the alternative result with probability `odds`
    return Math.random() - odds >= 0
      ? alternative.apply(context, args)
      : target.apply(context, args);
  }
});
  • source – the original function to proxy.
  • odds – probability of returning the alternative result (as a fraction of 1).
  • alternative – a fallback function to execute when the error occurs.

Example Usage

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

// 50 % chance of using the less‑accurate approximation
const roughArea = chaosProxy(circleArea, 0.5, circleAreaClose);

console.log(roughArea(2)); // → 12.566370614359172 (accurate)
console.log(roughArea(2)); // → 12.56 (approximate)

Running roughArea repeatedly will produce a mix of accurate and approximate results, illustrating how the proxy can inject nondeterministic behavior.

Extensions and Ideas

  • Multiple alternatives – assign different weights/probabilities to several fallback functions.
  • Async handling – manipulate Promise values or introduce random delays in asynchronous responses.
  • Argument mutation – modify the arguments object before forwarding to see how mutations affect your application.
  • Deterministic sequences – replace the random choice with a predefined sequence of responses for reproducible testing.

Experimenting with these variations can deepen your understanding of JavaScript’s proxy mechanics and help you build more resilient code.

Back to Blog

Related posts

Read more »

Building a CLI Adapter for Hono

Overview hono-cli-adapter lets you call Hono apps directly from the CLI. Your business logic stays in Hono, so you can debug with Postman or Insomnia, ship the...