@@ -78,15 +78,9 @@ function splitMultiIntoSingleValues(expr: string): string[] {
78
78
function parseAndReduce ( expr : string , fractionDigits = defaultFractionDigits ) : string | number {
79
79
let result : string | number = expr ;
80
80
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 ;
90
84
}
91
85
92
86
// 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
108
102
}
109
103
const resultUnit = Array . from ( foundUnits ) [ 0 ] ?? ( hasPx ? 'px' : '' ) ;
110
104
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
+ }
113
108
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
+ }
117
120
}
118
121
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
+ }
124
132
}
125
133
126
134
if ( typeof result !== 'number' ) {
135
+ // parsing failed, return the original expression
127
136
return result ;
128
137
}
129
138
0 commit comments