size.mjs 994 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const unitsSplit = /(-?[0-9.]*[0-9]+[0-9.]*)/g;
  2. const unitsTest = /^-?[0-9.]*[0-9]+[0-9.]*$/g;
  3. function calculateSize(size, ratio, precision) {
  4. if (ratio === 1) {
  5. return size;
  6. }
  7. precision = precision || 100;
  8. if (typeof size === "number") {
  9. return Math.ceil(size * ratio * precision) / precision;
  10. }
  11. if (typeof size !== "string") {
  12. return size;
  13. }
  14. const oldParts = size.split(unitsSplit);
  15. if (oldParts === null || !oldParts.length) {
  16. return size;
  17. }
  18. const newParts = [];
  19. let code = oldParts.shift();
  20. let isNumber = unitsTest.test(code);
  21. while (true) {
  22. if (isNumber) {
  23. const num = parseFloat(code);
  24. if (isNaN(num)) {
  25. newParts.push(code);
  26. } else {
  27. newParts.push(Math.ceil(num * ratio * precision) / precision);
  28. }
  29. } else {
  30. newParts.push(code);
  31. }
  32. code = oldParts.shift();
  33. if (code === void 0) {
  34. return newParts.join("");
  35. }
  36. isNumber = !isNumber;
  37. }
  38. }
  39. export { calculateSize };