Chaos Proxy:JavaScript 恶作剧

发布: (2025年12月28日 GMT+8 04:34)
2 分钟阅读
原文: Dev.to

Source: Dev.to

Chaos Proxy Overview

JavaScript Proxy 对象可以拦截并重新定义基础操作。此示例演示了一个简单的代理,它会根据可配置的错误概率,随机返回原函数的结果或替代结果。

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 – 要代理的原始函数。
  • odds – 返回替代结果的概率(以 1 为基准的分数)。
  • alternative – 当错误发生时执行的回退函数。

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)

反复运行 roughArea 将产生准确结果和近似结果的混合,展示了代理如何注入非确定性行为。

Extensions and Ideas

  • Multiple alternatives – 为多个回退函数分配不同的权重/概率。
  • Async handling – 操作 Promise 值或在异步响应中引入随机延迟。
  • Argument mutation – 在转发之前修改参数对象,以观察变更对应用的影响。
  • Deterministic sequences – 用预定义的响应序列替代随机选择,以实现可复现的测试。

尝试这些变体可以加深你对 JavaScript 代理机制的理解,并帮助你编写更具韧性的代码。

Back to Blog

相关文章

阅读更多 »