size.cjs 1022 B

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