Skip to content

Commit

Permalink
feat: 新增 indent
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed May 27, 2020
1 parent 8e9917a commit 905f8ab
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export * from 'lodash-es'

// @index(['./**/*.ts', '!./**/*.test.*'], f => `export * from '${f.path}'`)
export * from './utils/EventBus'
export * from './utils/indent'
export * from './utils/isPossibleChineseMobilePhoneNumber'
export * from './utils/isUrl'
// @endindex
32 changes: 32 additions & 0 deletions src/utils/indent.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { indent } from './indent'

describe(indent.name, () => {
test('空字符串正常', () => {
expect(indent``).toBe('')
})

test('首行无前导空白正常', () => {
expect(indent`${[1, 2].join('\n')}`).toBe('1\n2')
})

test('首行有前导空白正常', () => {
expect(indent` ${[1, 2].join('\n')}`).toBe(' 1\n 2')
})

test('非首行无前导空白正常', () => {
expect(indent`\n${[1, 2].join('\n')}`).toBe('\n1\n2')
expect(indent`\r\n${[1, 2].join('\n')}`).toBe('\r\n1\n2')
expect(indent`0\r\r\n${[1, 2].join('\n')}`).toBe('0\r\r\n1\n2')
})

test('非首行有前导空白正常', () => {
expect(indent`\n ${[1, 2].join('\n')}`).toBe('\n 1\n 2')
expect(indent`\r\n ${[1, 2].join('\n')}`).toBe('\r\n 1\n 2')
expect(indent`0 \r\r\n ${[1, 2].join('\n')}`).toBe('0 \r\r\n 1\n 2')
expect(indent`x \n\n ${[1, 2].join('\n')}`).toBe('x \n\n 1\n 2')
})

test('只处理紧跟前导空白后面的插入值', () => {
expect(indent`\n 0 ${[1, 2].join('\n')}`).toBe('\n 0 1\n2')
})
})
35 changes: 35 additions & 0 deletions src/utils/indent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* 每一行紧跟前导空白的插入值为多行时,保持缩进。
*
* ```
* indent` ${'a\nb'}` // => ' a\n b'
* ```
*
* @param literals 字面值
* @param interpolations 插入值
* @returns 返回处理后的结果
*/
export function indent(
literals: TemplateStringsArray,
...interpolations: string[]
): string {
let result = ''

for (let i = 0; i < interpolations.length; i++) {
const literal = literals[i]
let interpolation = interpolations[i]
const match = literal.match(/(?:^|[\r\n]+)([^\S\r\n]*)$/)
if (match && match[1]) {
interpolation = interpolation.replace(
/(?<=[\r\n]+)(?=[^\r\n])/g,
match[1],
)
}
result += literal
result += interpolation
}

result += literals[literals.length - 1]

return result
}
5 changes: 5 additions & 0 deletions src/utils/isUrl.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
/**
* 检测传入值是否是 URL。
*
* ```
* isUrl('foo.bar') // => false
* isUrl('http://foo.bar') // => true
* ```
*
* @param value 要检测的值
* @returns 返回检测结果
*/
Expand Down

0 comments on commit 905f8ab

Please sign in to comment.