Skip to content

Commit d67a5b3

Browse files
Improve performance by adding fast path for strings without ANSI codes (#54)
1 parent 03d7ab1 commit d67a5b3

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

index.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@ export default function stripAnsi(string) {
77
throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
88
}
99

10+
// Fast path: ANSI codes require ESC (7-bit) or CSI (8-bit) introducer
11+
if (!string.includes('\u001B') && !string.includes('\u009B')) {
12+
return string;
13+
}
14+
1015
// Even though the regex is global, we don't need to reset the `.lastIndex`
1116
// because unlike `.exec()` and `.test()`, `.replace()` does it automatically
1217
// and doing it manually has a performance penalty.

test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,15 @@ test('strip OSC sequence with BEL terminator', t => {
2222
const output = stripAnsi(input);
2323
t.is(output, 'ABC\r\n');
2424
});
25+
26+
test('strip color from string using 8-bit CSI introducer', t => {
27+
t.is(stripAnsi('\u009B31mfoo\u009B39m'), 'foo');
28+
});
29+
30+
test('return string as-is if no ANSI codes', t => {
31+
t.is(stripAnsi('foo bar'), 'foo bar');
32+
});
33+
34+
test('return empty string as-is', t => {
35+
t.is(stripAnsi(''), '');
36+
});

0 commit comments

Comments
 (0)