UNPKG

@orca-fe/x-map

Version:
112 lines (111 loc) 3.49 kB
export const once = (callback) => { let called = false; return ((...args) => { if (called) return undefined; called = true; return callback(...args); }); }; export function clamp(a, b, c) { return Math.max(b, Math.min(c, a)); } export function getDom(id) { if (typeof id === 'string') { return document.getElementById(id); } return id; } export const isNumber = v => !Number.isNaN(Number(v)); export const debounce = (callback, wait, options = {}) => { const { maxWait = Infinity } = options; let waiting = false; let firstWaitTime = 0; let timer = 0; // eslint-disable-next-line @typescript-eslint/no-explicit-any let callArgs = []; function call() { waiting = false; callback(...callArgs); } function debounced(...args) { callArgs = args; if (!waiting) { waiting = true; firstWaitTime = Date.now(); } clearTimeout(timer); timer = setTimeout(call, Math.min(wait, maxWait - (Date.now() - firstWaitTime))); } debounced.flush = call; debounced.cancel = () => { waiting = false; clearTimeout(timer); }; return debounced; }; export function isSame(num1, num2, diff) { return Math.abs(num1 - num2) <= diff; } export function alignNumber(num, targetNumber, diff) { return isSame(num, targetNumber, diff) ? targetNumber : num; } export function toFixedNumber(num, digits) { return Number(num.toFixed(digits)); } export function fitSize(targetSize, varySize, fitMode = 'contain', digit) { const ratioX = varySize[0] / targetSize[0]; const ratioY = varySize[1] / targetSize[1]; const method = fitMode === 'contain' ? Math.max : Math.min; const ratio = method(ratioX, ratioY); let point = [varySize[0] / ratio, varySize[1] / ratio]; if (digit != null) { point = point.map(n => Number(n.toFixed(digit))); } return point; } /** * 数字转成汉字 * @params num === 要转换的数字 * @return 汉字 * */ export function toChinesNum(num) { const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']; const unit = ['', '十', '百', '千', '万']; const getWan = (temp) => { const strArr = temp.toString().split('') .reverse(); let newNum = ''; const newArr = []; strArr.forEach((item, index) => { newArr.unshift(item === '0' ? changeNum[item] : changeNum[item] + unit[index]); }); const numArr = []; newArr.forEach((m, n) => { if (m !== '零') numArr.push(n); }); if (newArr.length > 1) { newArr.forEach((m, n) => { if (newArr[newArr.length - 1] === '零') { if (n <= numArr[numArr.length - 1]) { newNum += m; } } else { newNum += m; } }); } else { [newNum] = newArr; } return newNum; }; const overWan = Math.floor(num / 10000); let noWan = `${num % 10000}`; if (noWan.toString().length < 4) { noWan = `0${noWan}`; } return overWan ? `${getWan(overWan)}${getWan(noWan)}` : getWan(num); }