Skip to content

Instantly share code, notes, and snippets.

@trevdor
Created April 4, 2024 14:49
Show Gist options
  • Save trevdor/3cbb381f9ffec638b4524416234a7ca3 to your computer and use it in GitHub Desktop.
Save trevdor/3cbb381f9ffec638b4524416234a7ca3 to your computer and use it in GitHub Desktop.
Truncate middle
export function truncateMiddle(text: string, truncationLength: number) {
if (text.length <= truncationLength || truncationLength <= ELLIPSIS_WIDTH) {
return text;
}
// ceil to favor an extra char or two before vs after the ellipsis
const halfLength = Math.ceil((truncationLength - ELLIPSIS_WIDTH) / 2);
const preEllipsisText = text.substr(0, halfLength).trim();
const postEllipsisText = text
.substr(
text.length - (truncationLength - ELLIPSIS_WIDTH - preEllipsisText.length)
)
.trim();
return `${preEllipsisText}...${postEllipsisText}`;
}
describe("#truncateMiddle", () => {
it("does not modify a string that is too short to need truncation", () => {
const text = "Never confuse movement with action.";
expect(truncateMiddle(text, text.length + 1)).toEqual(text);
});
it("does not truncate below the width of the ellipsis", () => {
const text = "Never confuse movement with action.";
expect(truncateMiddle(text, 3)).toEqual(text);
});
it("overweights the first half of the string when truncation will not be balanced", () => {
const text = "Never confuse movement with action.";
expect(truncateMiddle(text, 4)).toEqual("N...");
expect(truncateMiddle(text, 8)).toEqual("Nev...n.");
});
it("ellides from the middle of a string to an odd length", () => {
const text =
"The first principle is that you must not fool yourself and you are the easiest person to fool.";
expect(truncateMiddle(text, 33)).toEqual(
"The first princ...person to fool."
);
});
it("ellides from the middle of a string to an even length", () => {
const text =
"The first principle is that you must not fool yourself and you are the easiest person to fool.";
expect(truncateMiddle(text, 34)).toEqual(
"The first princi...person to fool."
);
});
it("omits trailing space from the text before the ellipsis mark", () => {
const text = "Never confuse movement with action.";
expect(truncateMiddle(text, 15)).toEqual("Never...action.");
});
it("may produce a string shorter than specified if a leading space is trimmed from the second half", () => {
const text = "Never confuse movement with action.";
expect(truncateMiddle(text, 29)).toEqual("Never confuse...with action.");
expect(truncateMiddle(text, 29)).toHaveLength(28);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment