2
0
mirror of https://github.com/iconify/iconify.git synced 2024-12-14 06:28:24 +00:00
iconify/packages/utils/src/svg/size.ts

60 lines
1.2 KiB
TypeScript
Raw Normal View History

2020-04-28 09:47:35 +00:00
/**
* Regular expressions for calculating dimensions
*/
const unitsSplit = /(-?[0-9.]*[0-9]+[0-9.]*)/g;
const unitsTest = /^-?[0-9.]*[0-9]+[0-9.]*$/g;
/**
* Calculate second dimension when only 1 dimension is set
*/
export function calculateSize(
2020-04-28 09:47:35 +00:00
size: string | number,
ratio: number,
precision?: number
): string | number {
if (ratio === 1) {
return size;
}
precision = precision === void 0 ? 100 : precision;
if (typeof size === 'number') {
return Math.ceil(size * ratio * precision) / precision;
}
if (typeof size !== 'string') {
return size;
}
// Split code into sets of strings and numbers
const oldParts = size.split(unitsSplit);
if (oldParts === null || !oldParts.length) {
return size;
}
const newParts = [];
let code = oldParts.shift() as string;
let isNumber = unitsTest.test(code);
2020-04-28 09:47:35 +00:00
// eslint-disable-next-line no-constant-condition
while (true) {
if (isNumber) {
const num = parseFloat(code);
if (isNaN(num)) {
newParts.push(code);
} else {
newParts.push(Math.ceil(num * ratio * precision) / precision);
}
} else {
newParts.push(code);
}
// next
code = oldParts.shift() as string;
if (code === void 0) {
return newParts.join('');
}
isNumber = !isNumber;
}
}