Number.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. var OMIT_PLUSSIGN = /^(?:\+|(-))?0*(\d*)(?:\.0*|(\.\d*?)0*)?$/;
  2. var KEEP_PLUSSIGN = /^([\+\-])?0*(\d*)(?:\.0*|(\.\d*?)0*)?$/;
  3. var unsafeToRemovePlusSignAfter = {
  4. Dimension: true,
  5. Hash: true,
  6. Identifier: true,
  7. Number: true,
  8. Raw: true,
  9. UnicodeRange: true
  10. };
  11. function packNumber(value, item) {
  12. // omit plus sign only if no prev or prev is safe type
  13. var regexp = item && item.prev !== null && unsafeToRemovePlusSignAfter.hasOwnProperty(item.prev.data.type)
  14. ? KEEP_PLUSSIGN
  15. : OMIT_PLUSSIGN;
  16. // 100 -> '100'
  17. // 00100 -> '100'
  18. // +100 -> '100' (only when safe, e.g. omitting plus sign for 1px+1px leads to single dimension instead of two)
  19. // -100 -> '-100'
  20. // 0.123 -> '.123'
  21. // 0.12300 -> '.123'
  22. // 0.0 -> ''
  23. // 0 -> ''
  24. // -0 -> '-'
  25. value = String(value).replace(regexp, '$1$2$3');
  26. if (value === '' || value === '-') {
  27. value = '0';
  28. }
  29. return value;
  30. }
  31. module.exports = function(node, item) {
  32. node.value = packNumber(node.value, item);
  33. };
  34. module.exports.pack = packNumber;