diff --git a/src/__tests__/index.js b/src/__tests__/index.js index a00f8df..11fc629 100644 --- a/src/__tests__/index.js +++ b/src/__tests__/index.js @@ -42,6 +42,27 @@ test( '1ex' ) +test( + 'should reduce simple calc (5)', + testFixture, + 'calc(50px - (20px - 30px))', + '60px' +) + +test( + 'should reduce additions and subtractions (1)', + testFixture, + 'calc(100% - 10px + 20px)', + 'calc(100% + 10px)' +) + +test( + 'should reduce additions and subtractions (2)', + testFixture, + 'calc(100% + 10px - 20px)', + 'calc(100% - 10px)' +) + test( 'should ignore value surrounding calc function (1)', testFixture, @@ -168,6 +189,19 @@ test( 'calc(1px + 1)' ) +test( + 'should reduce consecutive substractions (#24) (1)', + testFixture, + 'calc(100% - 120px - 60px)', + 'calc(100% - 180px)' +) + +test( + 'should reduce consecutive substractions (#24) (2)', + testFixture, + 'calc(100% - 10px - 20px)', + 'calc(100% - 30px)' +) test( 'should produce simpler result (postcss-calc#25) (1)', diff --git a/src/lib/reducer.js b/src/lib/reducer.js index 6f1d19f..4d9b3d3 100644 --- a/src/lib/reducer.js +++ b/src/lib/reducer.js @@ -113,17 +113,32 @@ function reduceAddSubExpression(node, precision) { return reduce(node, precision) } // (something + value) + value => something + (value + value) - // (something - value) + value => something - (value + value) + // (something - value1) + value2 => something - (value2 - value1) // (something + value) - value => something + (value - value) - // (something - value) - value => something - (value - value) + // (something - value) - value => something - (value + value) else if (right.type === left.right.type) { node = Object.assign({ }, left) - node.right = reduce({ - type: 'MathExpression', - operator: op, - left: left.right, - right: right - }, precision) + if (left.operator === '-') { + node.right = reduce({ + type: 'MathExpression', + operator: op === '-' ? '+' : '-', + left: right, + right: left.right + }, precision) + node.operator = op === '-' ? '-' : '+'; + } + else { + node.right = reduce({ + type: 'MathExpression', + operator: op, + left: left.right, + right: right + }, precision) + } + if (node.right.value < 0) { + node.right.value *= -1; + node.operator = node.operator === '-' ? '+' : '-'; + } return reduce(node, precision) } }