Skip to content

Commit d281704

Browse files
committed
feat(utils): add getNodeAncestors
1 parent 2461be0 commit d281704

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

lib/util/getNodeAncestors.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
'use strict';
2+
3+
/**
4+
* Returns the list of parents for the node, starting from the closest parent.
5+
* @param {ASTNode} node - root node to start parent traversal
6+
* @returns {Array.<ASTNode>} List of nodes or empty
7+
*/
8+
function getNodeAncestors(node) {
9+
const ancestors = [];
10+
if (!node) {
11+
return ancestors;
12+
}
13+
14+
// eslint-disable-next-line no-cond-assign
15+
for (let parent = node; parent = parent.parent;) {
16+
ancestors.push(parent);
17+
}
18+
return ancestors;
19+
}
20+
21+
module.exports = getNodeAncestors;

tests/util/getNodeAncestors.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
'use strict';
2+
3+
const assert = require('assert');
4+
const getNodeAncestors = require('../../lib/util/getNodeAncestors');
5+
6+
describe('getNodeAncestors', () => {
7+
it('returns empty array for null node', () => {
8+
assert.deepEqual(getNodeAncestors(null), []);
9+
});
10+
it('returns list of parents', () => {
11+
const node = {
12+
type: 'Identifier',
13+
parent: {
14+
type: 'FunctionDeclaration',
15+
parent: {
16+
type: 'Program'
17+
}
18+
}
19+
};
20+
const actual = getNodeAncestors(node);
21+
const expected = ['FunctionDeclaration', 'Program'];
22+
23+
actual.forEach((parent, i) => assert.equal(parent.type, expected[i]));
24+
});
25+
});

0 commit comments

Comments
 (0)