Skip to content

Commit

Permalink
feat: add parseCSSValue
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Oct 14, 2018
1 parent 709b7f0 commit e04b587
Show file tree
Hide file tree
Showing 3 changed files with 82 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 @@ -25,6 +25,7 @@ export { default as isRegExp } from './isRegExp'
export { default as isString } from './isString'
export { default as isUndefined } from './isUndefined'
export { default as noop } from './noop'
export { default as parseCSSValue } from './parseCSSValue'
export { default as reduce } from './reduce'
export { default as repeat } from './repeat'
export { default as supportPassiveEventListener } from './supportPassiveEventListener'
28 changes: 28 additions & 0 deletions src/parseCSSValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* 解析 CSS 值的数值和单位。
*
* @param value 要解析的值
* @param [defaultUnit='px'] 默认单位
* @returns 解析结果
*/
export default function parseCSSValue(
value: string | number,
defaultUnit: string = 'px'
): { value: number, unit: string } {
if (typeof value === 'number') {
return {
value,
unit: defaultUnit
}
}
const matches = value.trim().match(/^(-?[\d+.-]+)([a-z]+|%)$/i)
return matches !== null
? {
value: Number(matches[1]),
unit: matches[2]
}
: {
value: Number(value),
unit: defaultUnit
}
}
53 changes: 53 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -457,3 +457,56 @@ describe('supportPassiveEventListener', () => {
expect(vtils.supportPassiveEventListener()).toBeFalsy()
})
})

describe('parseCSSValue', () => {
test('数字', () => {
expect(vtils.parseCSSValue(12)).toEqual({
value: 12,
unit: 'px'
})
expect(vtils.parseCSSValue(-4)).toEqual({
value: -4,
unit: 'px'
})
expect(vtils.parseCSSValue('12')).toEqual({
value: 12,
unit: 'px'
})
expect(vtils.parseCSSValue('-4')).toEqual({
value: -4,
unit: 'px'
})
})
test('CSS 值', () => {
expect(vtils.parseCSSValue('12px')).toEqual({
value: 12,
unit: 'px'
})
expect(vtils.parseCSSValue('-4px')).toEqual({
value: -4,
unit: 'px'
})
expect(vtils.parseCSSValue('10%')).toEqual({
value: 10,
unit: '%'
})
expect(vtils.parseCSSValue('2.5em')).toEqual({
value: 2.5,
unit: 'em'
})
expect(vtils.parseCSSValue('.399999rem')).toEqual({
value: .399999,
unit: 'rem'
})
})
test('默认单位', () => {
expect(vtils.parseCSSValue(12, 'em')).toEqual({
value: 12,
unit: 'em'
})
expect(vtils.parseCSSValue('12', 'em')).toEqual({
value: 12,
unit: 'em'
})
})
})

0 comments on commit e04b587

Please sign in to comment.