Skip to content

Commit 9f31731

Browse files
committed
chore: refactor determining whether to add parenthesis when stringifying
1 parent 14a8f4b commit 9f31731

File tree

2 files changed

+9
-6
lines changed

2 files changed

+9
-6
lines changed

src/stringify.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -72,15 +72,16 @@ export const stringify = (query: JSONQuery, options?: JSONQueryStringifyOptions)
7272

7373
const argsStr = args.map((child, index) => {
7474
const childName = child?.[0]
75-
const firstGroup = allOperators.filter((group) => name in group || childName in group)[0]
75+
const precedence = allOperators.findIndex((group) => name in group)
76+
const childPrecedence = allOperators.findIndex((group) => childName in group)
7677

77-
const higherPrecedence = !(name in firstGroup)
78+
const higherPrecedence = precedence > childPrecedence
79+
const isFirstArgument = index === 0 // we only support left associative operators
7880
const selfWithVarargSupport =
79-
name === childName && allVarargOperators.includes(op) && index === 0
80-
const leftWithSamePrecedence =
81-
name !== childName && name in firstGroup && childName in firstGroup && index === 0
81+
isFirstArgument && name === childName && allVarargOperators.includes(op)
82+
const notSelf = isFirstArgument && name !== childName
8283

83-
const noParenthesis = higherPrecedence || selfWithVarargSupport || leftWithSamePrecedence
84+
const noParenthesis = higherPrecedence || selfWithVarargSupport || notSelf
8485

8586
return _stringify(child, indent + space, !noParenthesis)
8687
})

test-suite/stringify.test.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,10 @@
8484
"tests": [
8585
{ "input": ["abs", ["add", 2, 3]], "output": "abs(2 + 3)" },
8686
{ "input": ["multiply", ["pow", 2, 3], 4], "output": "2 ^ 3 * 4" },
87+
{ "input": ["multiply", 2, ["pow", 3, 4]], "output": "2 * 3 ^ 4" },
8788
{ "input": ["pow", 2, ["multiply", 3, 4]], "output": "2 ^ (3 * 4)" },
8889
{ "input": ["add", ["multiply", 2, 3], 4], "output": "2 * 3 + 4" },
90+
{ "input": ["add", 2, ["multiply", 3, 4]], "output": "2 + 3 * 4" },
8991
{ "input": ["multiply", 2, ["add", 3, 4]], "output": "2 * (3 + 4)" },
9092
{ "input": ["gt", ["add", 2, 3], 4], "output": "2 + 3 > 4" },
9193
{ "input": ["add", 2, ["gt", 3, 4]], "output": "2 + (3 > 4)" },

0 commit comments

Comments
 (0)