mirror of
https://github.com/youzan/vant.git
synced 2026-03-26 02:03:21 +08:00
chore: move utils
This commit is contained in:
31
src-next/utils/format/number.ts
Normal file
31
src-next/utils/format/number.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
export function range(num: number, min: number, max: number): number {
|
||||
return Math.min(Math.max(num, min), max);
|
||||
}
|
||||
|
||||
function trimExtraChar(value: string, char: string, regExp: RegExp) {
|
||||
const index = value.indexOf(char);
|
||||
|
||||
if (index === -1) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (char === '-' && index !== 0) {
|
||||
return value.slice(0, index);
|
||||
}
|
||||
|
||||
return value.slice(0, index + 1) + value.slice(index).replace(regExp, '');
|
||||
}
|
||||
|
||||
export function formatNumber(value: string, allowDot?: boolean) {
|
||||
if (allowDot) {
|
||||
value = trimExtraChar(value, '.', /\./g);
|
||||
} else {
|
||||
value = value.split('.')[0];
|
||||
}
|
||||
|
||||
value = trimExtraChar(value, '-', /-/g);
|
||||
|
||||
const regExp = allowDot ? /[^-0-9.]/g : /[^-0-9]/g;
|
||||
|
||||
return value.replace(regExp, '');
|
||||
}
|
||||
15
src-next/utils/format/string.ts
Normal file
15
src-next/utils/format/string.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
const camelizeRE = /-(\w)/g;
|
||||
|
||||
export function camelize(str: string): string {
|
||||
return str.replace(camelizeRE, (_, c) => c.toUpperCase());
|
||||
}
|
||||
|
||||
export function padZero(num: number | string, targetLength = 2): string {
|
||||
let str = num + '';
|
||||
|
||||
while (str.length < targetLength) {
|
||||
str = '0' + str;
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
43
src-next/utils/format/unit.ts
Normal file
43
src-next/utils/format/unit.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { isDef } from '..';
|
||||
import { isNumeric } from '../validate/number';
|
||||
|
||||
export function addUnit(value?: string | number): string | undefined {
|
||||
if (!isDef(value)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
value = String(value);
|
||||
return isNumeric(value) ? `${value}px` : value;
|
||||
}
|
||||
|
||||
// cache
|
||||
let rootFontSize: number;
|
||||
|
||||
function getRootFontSize() {
|
||||
if (!rootFontSize) {
|
||||
const doc = document.documentElement;
|
||||
const fontSize =
|
||||
doc.style.fontSize || window.getComputedStyle(doc).fontSize;
|
||||
|
||||
rootFontSize = parseFloat(fontSize);
|
||||
}
|
||||
|
||||
return rootFontSize;
|
||||
}
|
||||
|
||||
function convertRem(value: string) {
|
||||
value = value.replace(/rem/g, '');
|
||||
return +value * getRootFontSize();
|
||||
}
|
||||
|
||||
export function unitToPx(value: string | number): number {
|
||||
if (typeof value === 'number') {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (value.indexOf('rem') !== -1) {
|
||||
return convertRem(value);
|
||||
}
|
||||
|
||||
return parseFloat(value);
|
||||
}
|
||||
Reference in New Issue
Block a user