Skip to content

fix(truncate): preserve separator boundaries - #2180

Merged
raon0211 merged 3 commits into
toss:mainfrom
subotac:fix/truncate-separator-boundaries
Nov 2, 2026
Merged

raon0211 merged 3 commits into
toss:mainfrom
subotac:fix/truncate-separator-boundaries

Conversation

@subotac

@subotac subotac commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #2172.

Match Lodash when a separator starts exactly at the truncation boundary or at the beginning of the string.

import { truncate as lodashTruncate } from 'lodash';
import { truncate } from 'es-toolkit/compat';

const options = { length: 14, separator: /,? +/ };

lodashTruncate('hello world remainder', options); // 'hello world...'
truncate('hello world remainder', options);
// Before: 'hello...'; after: 'hello world...'

lodashTruncate(' abcdef', { length: 5, separator: /,? +/ }); // '...'
truncate(' abcdef', { length: 5, separator: /,? +/ });
// Before: ' a...'; after: '...'

The Lodash calls compile against @types/lodash with strict: true.
The same separator is used in the Stratus truncation filter.

Changes

  • Preserve the retained prefix when a separator begins at the truncation boundary.
  • Handle string and regular-expression separators at index zero.
  • Advance past empty regular-expression matches, including Unicode matches, without changing the supplied expression's lastIndex.
  • Add regression tests and a bundle size benchmark (benchmarks/bundle-size/truncate.spec.ts).

Bundle size

truncate from es-toolkit/compat, bundled and minified with esbuild as in benchmarks/bundle-size:

main This PR
Minified 813 B 1,005 B (+192 B)
Minified + gzip 497 B 585 B (+88 B)

The escapeRegExp import is gone, but the boundary check and the loop that finds the last separator (including the step past empty matches) add more code than it saved. lodash-es is 5,354 B.

@vercel

vercel Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
es-toolkit Ready Ready Preview Nov 2, 2026 1:36am UTC

Request Review

@raon0211
raon0211 merged commit 9321d10 into toss:main Nov 2, 2026
13 checks passed

This branch was successfully deployed

1 active deployment
Preview — 4574ee7f Deployed Nov 2, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

compat/truncate: separator handling differs from lodash when the cut lands on a separator

2 participants