Files
bun.sh/bench/snippets/strip-ansi.mjs
Jarred Sumner 4fa69773a3 Introduce Bun.stripANSI (#21801)
### What does this PR do?

Introduce `Bun.stripANSI`, a SIMD-accelerated drop-in replacement for
the popular `"strip-ansi"` package.

`Bun.stripANSI` performs >10x faster and fixes several bugs in
`strip-ansi`, like [this long-standing
one](https://github.com/chalk/strip-ansi/issues/43).

### How did you verify your code works?

There are tests that check the output of `strip-ansi` matches
`Bun.stripANSI`. For cases where `strip-ansi`'s behavior is incorrect,
the expected value is manually provided.

---------

Co-authored-by: Jarred-Sumner <709451+Jarred-Sumner@users.noreply.github.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: taylor.fish <contact@taylor.fish>
2025-08-14 22:42:05 -07:00

38 lines
1007 B
JavaScript

import npmStripAnsi from "strip-ansi";
import { bench, run } from "../runner.mjs";
let bunStripANSI = null;
if (!process.env.FORCE_NPM) {
bunStripANSI = globalThis?.Bun?.stripANSI;
}
const stripANSI = bunStripANSI || npmStripAnsi;
const formatter = new Intl.NumberFormat();
const format = n => {
return formatter.format(n);
};
const inputs = [
["hello world", "no-ansi"],
["\x1b[31mred\x1b[39m", "ansi"],
["a".repeat(1024 * 16), "long-no-ansi"],
["\x1b[31mred\x1b[39m".repeat(1024 * 16), "long-ansi"],
];
const maxInputLength = Math.max(...inputs.map(([input]) => input.length));
for (const [input, textLabel] of inputs) {
const label = bunStripANSI ? "Bun.stripANSI" : "npm/strip-ansi";
const name = `${label} ${format(input.length).padStart(format(maxInputLength).length, " ")} chars ${textLabel}`;
bench(name, () => {
stripANSI(input);
});
if (bunStripANSI && bunStripANSI(input) !== npmStripAnsi(input)) {
throw new Error("strip-ansi mismatch");
}
}
await run();