Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Insert more needed parenthesis #116

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/__tests__/index.js
Expand Up @@ -445,6 +445,13 @@ test(
'calc(unknown(safe-area-inset-left))',
);

test(
'should correctly preserve parentheses'
testValue,
'calc(1/((var(--a) - var(--b)) / 16))',
'calc(1/((var(--a) - var(--b)) / 16))'
)

test(
'should preserve the original declaration when `preserve` option is set to true',
testCss,
Expand Down
28 changes: 26 additions & 2 deletions src/lib/stringifier.js
Expand Up @@ -5,6 +5,30 @@ const order = {
"-": 1,
};

var nonAssociative = {
'*': false,
'/': true,
'+': false,
'-': true
}

function needsParenthesis(op, childOp){
let opOrder = order[op];
let childOpOrder = order[childOp];
if (opOrder === childOpOrder){
// Chains of the same operation only need parenthesis if non-associative
if (op === childOp){
return nonAssociative[op];
} else {
// Same precedence but different operator: always
return true;
}
} else {
// Follow operator precendence
return order[op] < order[childOp];
}
}

function round(value, prec) {
if (prec !== false) {
const precision = Math.pow(10, prec);
Expand All @@ -19,15 +43,15 @@ function stringify(node, prec) {
const {left, right, operator: op} = node;
let str = "";

if (left.type === 'MathExpression' && order[op] < order[left.operator]) {
if (left.type === 'MathExpression' && needsParenthesis(op, left.operator)) {
str += `(${stringify(left, prec)})`;
} else {
str += stringify(left, prec);
}

str += order[op] ? ` ${node.operator} ` : node.operator;

if (right.type === 'MathExpression' && order[op] < order[right.operator]) {
if (right.type === 'MathExpression' && needsParenthesis(op, right.operator)) {
str += `(${stringify(right, prec)})`;
} else {
str += stringify(right, prec);
Expand Down