sizeUtil.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
  2. export function autoPtgSizes(ptgSizes, minPtgSizes, maxPtgSizes) {
  3. // Static current data
  4. let currentTotalPtg = 0;
  5. const undefinedIndexes = [];
  6. ptgSizes.forEach((size, index) => {
  7. if (size === undefined) {
  8. undefinedIndexes.push(index);
  9. } else {
  10. currentTotalPtg += size;
  11. }
  12. });
  13. const restPtg = 1 - currentTotalPtg;
  14. const undefinedCount = undefinedIndexes.length;
  15. // Fill if exceed
  16. if (restPtg < 0) {
  17. const scale = 1 / currentTotalPtg;
  18. return ptgSizes.map(size => size === undefined ? 0 : size * scale);
  19. }
  20. // Check if limit exists
  21. let sumMin = 0;
  22. let sumMax = 0;
  23. let limitMin = 0;
  24. let limitMax = 1;
  25. for (const index of undefinedIndexes) {
  26. const min = minPtgSizes[index] || 0;
  27. const max = maxPtgSizes[index] || 1;
  28. sumMin += min;
  29. sumMax += max;
  30. limitMin = Math.max(limitMin, min);
  31. limitMax = Math.min(limitMax, max);
  32. }
  33. // Impossible case, just average fill
  34. if (sumMin > 1 && sumMax < 1) {
  35. const avg = 1 / undefinedCount;
  36. return ptgSizes.map(size => size === undefined ? avg : size);
  37. }
  38. // Quickly fill if can
  39. const restAvg = restPtg / undefinedCount;
  40. if (limitMin <= restAvg && restAvg <= limitMax) {
  41. return ptgSizes.map(size => size === undefined ? restAvg : size);
  42. }
  43. // Greedy algorithm
  44. const result = _toConsumableArray(ptgSizes);
  45. let remain = restPtg - sumMin;
  46. for (let i = 0; i < undefinedCount; i += 1) {
  47. const index = undefinedIndexes[i];
  48. const min = minPtgSizes[index] || 0;
  49. const max = maxPtgSizes[index] || 1;
  50. result[index] = min;
  51. const canAdd = max - min;
  52. const add = Math.min(canAdd, remain);
  53. result[index] += add;
  54. remain -= add;
  55. }
  56. return result;
  57. }