Skip to content

Commit

Permalink
feat(utils): 新增 toSingleLineString
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Mar 22, 2023
1 parent 5b68544 commit 2e43ceb
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ export * from './signal'
export * from './swap'
export * from './toFullWidthString'
export * from './toHalfWidthString'
export * from './toSingleLineString'
export * from './traverse'
export * from './TreeData'
export * from './wait'
Expand Down
17 changes: 17 additions & 0 deletions src/utils/toSingleLineString.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { toSingleLineString } from './toSingleLineString'

describe('toSingleLineString', () => {
test('ok', () => {
expect(toSingleLineString('a\rb')).toBe('a b')
expect(toSingleLineString('a\r\n\n\r\nb')).toBe('a b')
expect(toSingleLineString('a\r\n\n\r\nb\r\n')).toBe('a b')
expect(toSingleLineString('a\r\n\n\r\nb\r\nc')).toBe('a b c')
expect(toSingleLineString('\r\n\n\r\n')).toBe('')
expect(toSingleLineString('a\rb\ncvldlddd', 5)).toBe('a ...')
expect(
toSingleLineString('a\rb\ncvldlddd', {
length: 5,
}),
).toBe('a ...')
})
})
24 changes: 24 additions & 0 deletions src/utils/toSingleLineString.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { truncate } from 'lodash-uni'
import type { TruncateOptions } from 'lodash'

/**
* 将多行字符串转换为单行字符串。
*
* @param value 要转换的字符串
* @returns 返回结果
*/
export function toSingleLineString(
value: string,
truncateOptions?: number | TruncateOptions,
): string {
let res = value.replace(/[\r\n]+/g, ' ').trim()
if (truncateOptions) {
res = truncate(
res,
typeof truncateOptions === 'number'
? { length: truncateOptions }
: truncateOptions,
)
}
return res
}

0 comments on commit 2e43ceb

Please sign in to comment.