Skip to content

Commit 3a1eedb

Browse files
jviidemichaelficarra
authored andcommitted
Create fewer intermediate objects in inPath
1 parent d48605a commit 3a1eedb

1 file changed

Lines changed: 18 additions & 12 deletions

File tree

esquery.js

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -46,21 +46,27 @@ function getPath(obj, keys) {
4646
* @param {?external:AST} node
4747
* @param {?external:AST} ancestor
4848
* @param {string[]} path
49+
* @param {Integer} fromPathIndex
4950
* @returns {boolean}
5051
*/
51-
function inPath(node, ancestor, path) {
52-
if (path.length === 0) { return node === ancestor; }
53-
if (ancestor == null) { return false; }
54-
const field = ancestor[path[0]];
55-
const remainingPath = path.slice(1);
56-
if (Array.isArray(field)) {
57-
for (let i = 0; i < field.length; i++) {
58-
if (inPath(node, field[i], remainingPath)) { return true; }
52+
function inPath(node, ancestor, path, fromPathIndex) {
53+
let current = ancestor;
54+
for (let i = fromPathIndex; i < path.length; i++) {
55+
if (current == null) {
56+
return false;
5957
}
60-
return false;
61-
} else {
62-
return inPath(node, field, remainingPath);
58+
const field = current[path[i]];
59+
if (Array.isArray(field)) {
60+
for (let j = 0; j < field.length; j++) {
61+
if (inPath(node, field[j], path, i + 1)) {
62+
return true;
63+
}
64+
}
65+
return false;
66+
}
67+
current = field;
6368
}
69+
return node === current;
6470
}
6571

6672
function createMatcher(selector) {
@@ -77,7 +83,7 @@ function createMatcher(selector) {
7783
const path = selector.name.split('.');
7884
return (node, ancestry) => {
7985
const ancestor = ancestry[path.length - 1];
80-
return inPath(node, ancestor, path);
86+
return inPath(node, ancestor, path, 0);
8187
};
8288
}
8389
case 'matches': {

0 commit comments

Comments
 (0)