Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 47 additions & 2 deletions common/src/util/__tests__/string.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,52 @@
import { describe, expect, it } from 'bun:test'

import { pluralize } from '../string'
import { pluralize, truncateStringWithMessage } from '../string'

describe('truncateStringWithMessage', () => {
it('should keep the truncation marker within maxLength for end truncation', () => {
const result = truncateStringWithMessage({
str: 'abcdefghijklmnopqrstuvwxyz',
maxLength: 10,
})

expect(result).toHaveLength(10)
expect(result).toBe('\n[TRUNCATE')
})

it('should keep the truncation marker within maxLength for start truncation', () => {
const result = truncateStringWithMessage({
str: 'abcdefghijklmnopqrstuvwxyz',
maxLength: 10,
remove: 'START',
})

expect(result).toHaveLength(10)
expect(result).toBe('[...TRUNCA')
})

it('should keep the truncation marker within maxLength for middle truncation', () => {
const result = truncateStringWithMessage({
str: 'abcdefghijklmnopqrstuvwxyz',
maxLength: 10,
remove: 'MIDDLE',
})

expect(result).toHaveLength(10)
expect(result).toBe('\n[...TRUNC')
})

it('should preserve context around the marker when maxLength allows it', () => {
const result = truncateStringWithMessage({
str: 'abcdefghijklmnopqrstuvwxyz',
maxLength: 19,
message: 'CUT',
remove: 'MIDDLE',
})

expect(result).toBe('abc\n[...CUT...]\nxyz')
expect(result).toHaveLength(19)
})
})

describe('pluralize', () => {
it('should handle singular and plural cases correctly', () => {
Expand Down Expand Up @@ -236,4 +282,3 @@ describe('pluralize', () => {
expect(pluralize(2, 'dependency')).toBe('2 dependencies')
})
})

9 changes: 9 additions & 0 deletions common/src/util/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,23 @@ export const truncateStringWithMessage = ({

if (remove === 'END') {
const suffix = `\n[${message}...]`
if (suffix.length >= maxLength) {
return suffix.slice(0, maxLength)
}
return str.slice(0, maxLength - suffix.length) + suffix
}
if (remove === 'START') {
const prefix = `[...${message}]\n`
if (prefix.length >= maxLength) {
return prefix.slice(0, maxLength)
}
return prefix + str.slice(str.length - maxLength + prefix.length)
}

const middle = `\n[...${message}...]\n`
if (middle.length >= maxLength) {
return middle.slice(0, maxLength)
}
const length = Math.floor((maxLength - middle.length) / 2)
return str.slice(0, length) + middle + str.slice(-length)
}
Expand Down