Skip to content

Commit 7cea93e

Browse files
committed
fix: a minor performance improvement in parse
1 parent f7bf200 commit 7cea93e

File tree

2 files changed

+10
-8
lines changed

2 files changed

+10
-8
lines changed

src/parse.ts

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ import type { JSONQuery, JSONQueryParseOptions } from './types'
2626
* // ]
2727
*/
2828
export function parse(query: string, options?: JSONQueryParseOptions): JSONQuery {
29+
const allOperators = { ...operators, ...options?.operators }
30+
const sortedOperatorNames = Object.keys(allOperators).sort((a, b) => b.length - a.length)
31+
2932
const parsePipe = () => {
3033
skipWhitespace()
3134
const first = parseOperator()
@@ -48,19 +51,18 @@ export function parse(query: string, options?: JSONQueryParseOptions): JSONQuery
4851
}
4952

5053
const parseOperator = () => {
51-
const allOperators = { ...operators, ...options?.operators }
5254

53-
const left = parseParentheses()
55+
const left = parseParenthesis()
5456

5557
skipWhitespace()
5658

5759
// we sort the operators from longest to shortest, so we first handle "<=" and next "<"
58-
for (const name of Object.keys(allOperators).sort((a, b) => b.length - a.length)) {
60+
for (const name of sortedOperatorNames) {
5961
const op = allOperators[name]
6062
if (query.substring(i, i + op.length) === op) {
6163
i += op.length
6264
skipWhitespace()
63-
const right = parseParentheses()
65+
const right = parseParenthesis()
6466

6567
return [name, left, right]
6668
}
@@ -69,7 +71,7 @@ export function parse(query: string, options?: JSONQueryParseOptions): JSONQuery
6971
return left
7072
}
7173

72-
const parseParentheses = () => {
74+
const parseParenthesis = () => {
7375
if (query[i] === '(') {
7476
i++
7577
const inner = parsePipe()
@@ -81,9 +83,9 @@ export function parse(query: string, options?: JSONQueryParseOptions): JSONQuery
8183
}
8284

8385
const parseProperty = () => {
84-
const props = []
85-
8686
if (query[i] === '.') {
87+
const props = []
88+
8789
while (query[i] === '.') {
8890
i++
8991

src/stringify.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ export const stringify = (query: JSONQuery, options?: JSONQueryStringifyOptions)
7676
const childIndent = args.length === 1 ? indent : indent + space
7777
const argsStr = args.map((arg) => _stringify(arg, childIndent))
7878
return args.length === 1 && argsStr[0][0] === '('
79-
? `${name}${argsStr}`
79+
? `${name}${argsStr[0]}`
8080
: join(
8181
argsStr,
8282
[`${name}(`, ', ', ')'],

0 commit comments

Comments
 (0)