@@ -78,15 +78,9 @@ function splitMultiIntoSingleValues(expr: string): string[] {
7878function parseAndReduce ( expr : string , fractionDigits = defaultFractionDigits ) : string | number {
7979 let result : string | number = expr ;
8080
81- let evaluated ;
82- // Try to evaluate as expr-eval expression
83- try {
84- evaluated = parser . evaluate ( `${ result } ` ) ;
85- if ( typeof evaluated === 'number' ) {
86- result = evaluated ;
87- }
88- } catch ( ex ) {
89- //
81+ // Check if expression is already a number
82+ if ( ! isNaN ( Number ( result ) ) ) {
83+ return result ;
9084 }
9185
9286 // We check for px unit, then remove it, since these are essentially numbers in tokens context
@@ -108,22 +102,37 @@ function parseAndReduce(expr: string, fractionDigits = defaultFractionDigits): s
108102 }
109103 const resultUnit = Array . from ( foundUnits ) [ 0 ] ?? ( hasPx ? 'px' : '' ) ;
110104
111- // Remove it here so we can evaluate expressions like 16px + 24px
112- const calcParsed = parse ( noPixExpr , { allowInlineCommnets : false } ) ;
105+ if ( ! isNaN ( Number ( noPixExpr ) ) ) {
106+ result = Number ( noPixExpr ) ;
107+ }
113108
114- // No expression to evaluate, just return it (in case of number as string e.g. '10')
115- if ( calcParsed . nodes . length === 1 && calcParsed . nodes [ 0 ] . type === 'Number' ) {
116- return `${ result } ` ;
109+ if ( typeof result !== 'number' ) {
110+ // Try to evaluate as expr-eval expression
111+ let evaluated ;
112+ try {
113+ evaluated = parser . evaluate ( `${ noPixExpr } ` ) ;
114+ if ( typeof evaluated === 'number' ) {
115+ result = evaluated ;
116+ }
117+ } catch ( ex ) {
118+ // no-op
119+ }
117120 }
118121
119- // Attempt to reduce the math expression
120- const reduced = reduceExpression ( calcParsed ) ;
121- // E.g. if type is Length, like 4 * 7rem would be 28rem
122- if ( reduced ) {
123- result = reduced . value ;
122+ if ( typeof result !== 'number' ) {
123+ // Try to evaluate as postcss-calc-ast-parser expression
124+ const calcParsed = parse ( noPixExpr , { allowInlineCommnets : false } ) ;
125+
126+ // Attempt to reduce the math expression
127+ const reduced = reduceExpression ( calcParsed ) ;
128+ // E.g. if type is Length, like 4 * 7rem would be 28rem
129+ if ( reduced ) {
130+ result = reduced . value ;
131+ }
124132 }
125133
126134 if ( typeof result !== 'number' ) {
135+ // parsing failed, return the original expression
127136 return result ;
128137 }
129138
0 commit comments