Skip to content

Commit

Permalink
feat: add padStart, padEnd
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jan 17, 2019
1 parent 9d59e41 commit 7a2cc5d
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ export { default as mapValues } from './mapValues'
export { default as noop } from './noop'
export { default as objectToQueryString } from './objectToQueryString'
export { default as omit } from './omit'
export { default as padEnd } from './padEnd'
export { default as padStart } from './padStart'
export { default as parseCSSValue } from './parseCSSValue'
export { default as pick } from './pick'
export { default as placeKitten } from './placeKitten'
Expand Down
18 changes: 18 additions & 0 deletions src/padEnd.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import repeat from './repeat'

/**
* 在 str 右侧填充字符。
*
* @param str 要填充的字符串
* @param [length=0] 目标长度
* @param [chars=' '] 填充字符
* @returns 填充后的字符串
*/
export default function padEnd(str: string, length: number = 0, chars: string = ' '): string {
let suffix = ''
if (length > str.length) {
const suffixLength = length - str.length
suffix = repeat(chars, length - str.length).slice(0, suffixLength)
}
return str + suffix
}
18 changes: 18 additions & 0 deletions src/padStart.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import repeat from './repeat'

/**
* 在 str 左侧填充字符。
*
* @param str 要填充的字符串
* @param [length=0] 目标长度
* @param [chars=' '] 填充字符
* @returns 填充后的字符串
*/
export default function padStart(str: string, length: number = 0, chars: string = ' '): string {
let prefix = ''
if (length > str.length) {
const prefixLength = length - str.length
prefix = repeat(chars, length - str.length).slice(0, prefixLength)
}
return prefix + str
}
18 changes: 18 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1446,3 +1446,21 @@ describe('placeKitten', () => {
expect(vtils.placeKitten(200, 100)).toMatch(/200\/100/)
})
})

describe('padStart', () => {
test('ok', () => {
expect(vtils.padStart('1', 3, '0')).toBe('001')
expect(vtils.padStart('abc', 6)).toBe(' abc')
expect(vtils.padStart('abc', 6, '_-')).toBe('_-_abc')
expect(vtils.padStart('abc', 3)).toBe('abc')
})
})

describe('padEnd', () => {
test('ok', () => {
expect(vtils.padEnd('1', 3, '0')).toBe('100')
expect(vtils.padEnd('abc', 6)).toBe('abc ')
expect(vtils.padEnd('abc', 6, '_-')).toBe('abc_-_')
expect(vtils.padEnd('abc', 3)).toBe('abc')
})
})

0 comments on commit 7a2cc5d

Please sign in to comment.