math.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. "use strict";
  2. exports.__esModule = true;
  3. exports["default"] = math;
  4. var _defaultSymbols = _interopRequireDefault(require("./presets/defaultSymbols"));
  5. var _errors = _interopRequireDefault(require("../internalHelpers/_errors"));
  6. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7. function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
  8. var unitRegExp = /((?!\w)a|na|hc|mc|dg|me[r]?|xe|ni(?![a-zA-Z])|mm|cp|tp|xp|q(?!s)|hv|xamv|nimv|wv|sm|s(?!\D|$)|ged|darg?|nrut)/g;
  9. // Merges additional math functionality into the defaults.
  10. function mergeSymbolMaps(additionalSymbols) {
  11. var symbolMap = {};
  12. symbolMap.symbols = additionalSymbols ? _extends({}, _defaultSymbols["default"].symbols, additionalSymbols.symbols) : _extends({}, _defaultSymbols["default"].symbols);
  13. return symbolMap;
  14. }
  15. function exec(operators, values) {
  16. var _ref;
  17. var op = operators.pop();
  18. values.push(op.f.apply(op, (_ref = []).concat.apply(_ref, values.splice(-op.argCount))));
  19. return op.precedence;
  20. }
  21. function calculate(expression, additionalSymbols) {
  22. var symbolMap = mergeSymbolMaps(additionalSymbols);
  23. var match;
  24. var operators = [symbolMap.symbols['('].prefix];
  25. var values = [];
  26. var pattern = new RegExp( // Pattern for numbers
  27. "\\d+(?:\\.\\d+)?|" +
  28. // ...and patterns for individual operators/function names
  29. Object.keys(symbolMap.symbols).map(function (key) {
  30. return symbolMap.symbols[key];
  31. })
  32. // longer symbols should be listed first
  33. // $FlowFixMe
  34. .sort(function (a, b) {
  35. return b.symbol.length - a.symbol.length;
  36. })
  37. // $FlowFixMe
  38. .map(function (val) {
  39. return val.regSymbol;
  40. }).join('|') + "|(\\S)", 'g');
  41. pattern.lastIndex = 0; // Reset regular expression object
  42. var afterValue = false;
  43. do {
  44. match = pattern.exec(expression);
  45. var _ref2 = match || [')', undefined],
  46. token = _ref2[0],
  47. bad = _ref2[1];
  48. var notNumber = symbolMap.symbols[token];
  49. var notNewValue = notNumber && !notNumber.prefix && !notNumber.func;
  50. var notAfterValue = !notNumber || !notNumber.postfix && !notNumber.infix;
  51. // Check for syntax errors:
  52. if (bad || (afterValue ? notAfterValue : notNewValue)) {
  53. throw new _errors["default"](37, match ? match.index : expression.length, expression);
  54. }
  55. if (afterValue) {
  56. // We either have an infix or postfix operator (they should be mutually exclusive)
  57. var curr = notNumber.postfix || notNumber.infix;
  58. do {
  59. var prev = operators[operators.length - 1];
  60. if ((curr.precedence - prev.precedence || prev.rightToLeft) > 0) break;
  61. // Apply previous operator, since it has precedence over current one
  62. } while (exec(operators, values)); // Exit loop after executing an opening parenthesis or function
  63. afterValue = curr.notation === 'postfix';
  64. if (curr.symbol !== ')') {
  65. operators.push(curr);
  66. // Postfix always has precedence over any operator that follows after it
  67. if (afterValue) exec(operators, values);
  68. }
  69. } else if (notNumber) {
  70. // prefix operator or function
  71. operators.push(notNumber.prefix || notNumber.func);
  72. if (notNumber.func) {
  73. // Require an opening parenthesis
  74. match = pattern.exec(expression);
  75. if (!match || match[0] !== '(') {
  76. throw new _errors["default"](38, match ? match.index : expression.length, expression);
  77. }
  78. }
  79. } else {
  80. // number
  81. values.push(+token);
  82. afterValue = true;
  83. }
  84. } while (match && operators.length);
  85. if (operators.length) {
  86. throw new _errors["default"](39, match ? match.index : expression.length, expression);
  87. } else if (match) {
  88. throw new _errors["default"](40, match ? match.index : expression.length, expression);
  89. } else {
  90. return values.pop();
  91. }
  92. }
  93. function reverseString(str) {
  94. return str.split('').reverse().join('');
  95. }
  96. /**
  97. * Helper for doing math with CSS Units. Accepts a formula as a string. All values in the formula must have the same unit (or be unitless). Supports complex formulas utliziing addition, subtraction, multiplication, division, square root, powers, factorial, min, max, as well as parentheses for order of operation.
  98. *
  99. *In cases where you need to do calculations with mixed units where one unit is a [relative length unit](https://developer.mozilla.org/en-US/docs/Web/CSS/length#Relative_length_units), you will want to use [CSS Calc](https://developer.mozilla.org/en-US/docs/Web/CSS/calc).
  100. *
  101. * *warning* While we've done everything possible to ensure math safely evalutes formulas expressed as strings, you should always use extreme caution when passing `math` user provided values.
  102. * @example
  103. * // Styles as object usage
  104. * const styles = {
  105. * fontSize: math('12rem + 8rem'),
  106. * fontSize: math('(12px + 2px) * 3'),
  107. * fontSize: math('3px^2 + sqrt(4)'),
  108. * }
  109. *
  110. * // styled-components usage
  111. * const div = styled.div`
  112. * fontSize: ${math('12rem + 8rem')};
  113. * fontSize: ${math('(12px + 2px) * 3')};
  114. * fontSize: ${math('3px^2 + sqrt(4)')};
  115. * `
  116. *
  117. * // CSS as JS Output
  118. *
  119. * div: {
  120. * fontSize: '20rem',
  121. * fontSize: '42px',
  122. * fontSize: '11px',
  123. * }
  124. */
  125. function math(formula, additionalSymbols) {
  126. var reversedFormula = reverseString(formula);
  127. var formulaMatch = reversedFormula.match(unitRegExp);
  128. // Check that all units are the same
  129. if (formulaMatch && !formulaMatch.every(function (unit) {
  130. return unit === formulaMatch[0];
  131. })) {
  132. throw new _errors["default"](41);
  133. }
  134. var cleanFormula = reverseString(reversedFormula.replace(unitRegExp, ''));
  135. return "" + calculate(cleanFormula, additionalSymbols) + (formulaMatch ? reverseString(formulaMatch[0]) : '');
  136. }
  137. module.exports = exports.default;