Anthropic

Claude Opus 5.5

Anthropic's most capable model for long, careful work where getting it right matters most.

  • Code review
  • Complex analysis
  • Long-form writing

Made with Claude Opus 5.5

Real output from our prompts, unedited.

Write a TypeScript function `debounceAsync` that debounces an async function, cancels stale calls with AbortController and always resolves the latest call. Include a short usage example.

debounceAsync: Debounce with Abort and Latest-Result Resolution

Behavior

  • Debounces calls. Only the last call within wait ms actually runs.
  • Aborts stale work. If a new call arrives while a previous execution is in flight, that execution's AbortSignal fires.
  • Always resolves to the latest call. Every pending caller, including superseded ones, receives the result of the most recent call. No promise is left hanging.

Implementation

ts
type AsyncFn<A extends unknown[], R> = (signal: AbortSignal, ...args: A) => Promise<R>;

interface Waiter<R> {
  resolve: (value: R) => void;
  reject: (reason: unknown) => void;
}

export function debounceAsync<A extends unknown[], R>(fn: AsyncFn<A, R>, wait: number) {
  let timer: ReturnType<typeof setTimeout> | undefined;
  let controller: AbortController | undefined;
  let waiters: Waiter<R>[] = [];
  let latestId = 0;

  const settle = (cb: (w: Waiter<R>) => void) => {
    const batch = waiters;
    waiters = [];
    batch.forEach(cb);
  };

  const debounced = (...args: A): Promise<R> => {
    const id = ++latestId;
    clearTimeout(timer);
    controller?.abort(); // cancel any stale in-flight execution

    return new Promise<R>((resolve, reject) => {
      waiters.push({ resolve, reject });

      timer = setTimeout(async () => {
        const ctrl = new AbortController();
        controller = ctrl;
        try {
          const result = await fn(ctrl.signal, ...args);
          if (id === latestId) settle((w) => w.resolve(result));
        } catch (err) {
          // Ignore errors from superseded runs; the newer call will settle waiters.
          if (id === latestId) settle((w) => w.reject(err));
        } finally {
          if (controller === ctrl) controller = undefined;
        }
      }, wait);
    });
  };

  /** Cancel pending/in-flight work and reject all waiters. */
  debounced.cancel = () => {
    latestId++;
    clearTimeout(timer);
    controller?.abort();
    settle((w) => w.reject(new DOMException("Cancelled", "AbortError")));
  };

  return debounced;
}

Usage Example

ts
const search = debounceAsync(async (signal, query: string) => {
  const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return (await res.json()) as string[];
}, 300);

// Rapid typing: only "react" is fetched, and all three promises resolve with its results.
search("r").then((r) => console.log("r →", r));
search("re").then((r) => console.log("re →", r));
search("react").then((r) => console.log("react →", r));

// On component unmount:
// search.cancel();

Notes

  • The signal is the first parameter. Your function must pass signal to cancellable APIs such as fetch. Otherwise, aborting only discards the stale result and does not stop the work.
  • Stale errors are swallowed. An AbortError from a superseded run never reaches callers. The latest call settles everyone.
  • Rejecting instead of sharing results. If you prefer that superseded callers reject rather than receive the latest result, reject the older waiters with an AbortError inside debounced before pushing the new waiter.

A bag has 4 red, 5 blue and 6 green marbles. You draw three without replacement. What is the probability that all three are different colours? Show your working and give the answer as a fraction.

Probability That All Three Marbles Are Different Colours

Setting Up

The bag contains:

  • 4 red
  • 5 blue
  • 6 green

That is 15 marbles in total, and we draw 3 without replacement. Since order doesn't matter, we can count combinations.

Step 1: Total Possible Outcomes

The number of ways to choose any 3 marbles from 15 is:

$$ \binom{15}{3} = \frac{15 \times 14 \times 13}{3 \times 2 \times 1} = \frac{2730}{6} = 455 $$

Step 2: Favourable Outcomes

For all three to be different colours, we need exactly one red, one blue and one green:

$$ \binom{4}{1} \times \binom{5}{1} \times \binom{6}{1} = 4 \times 5 \times 6 = 120 $$

Step 3: Compute the Probability

$$ P(\text{all different}) = \frac{120}{455} $$

Simplify by dividing numerator and denominator by 5:

$$ \frac{120}{455} = \frac{24}{91} $$

Check Using Sequential Draws

Find the probability of one particular colour order, such as Red → Blue → Green:

$$ \frac{4}{15} \times \frac{5}{14} \times \frac{6}{13} = \frac{120}{2730} $$

There are $3! = 6$ possible orders of the three colours, and each has the same probability:

$$ 6 \times \frac{120}{2730} = \frac{720}{2730} = \frac{24}{91} \checkmark $$

Answer

$$ \boxed{P = \dfrac{24}{91} \approx 0.264} $$

There is roughly a 26.4% chance that the three marbles drawn are all different colours.

Write a warm, three-sentence thank-you note to a colleague who covered my shifts while I was sick.

Thank-You Note

Dear [Name],

Thank you so much for covering my shifts while I was out sick. Knowing everything was in such capable hands let me focus on resting and getting better, and that meant more to me than I can say. I'm truly grateful to have a colleague like you, and I'd love to return the favor, starting with coffee on me this week!

Warmly, [Your Name]

Specs

Anthropic's most capable model for complex work.

Context window
200K tokens
Longest reply
16K tokens
Thinks before answering
Yes
Understands images
Yes
Reads PDFs
Yes
Web search and tools
Yes

Compare with