chore: move utils

This commit is contained in:
chenjiahan
2020-07-05 08:32:49 +08:00
parent 0a4c6676ba
commit 12faaa2179
20 changed files with 776 additions and 2 deletions

View 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, '');
}

View 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;
}

View 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);
}