Skip to content

Commit

Permalink
add childNodesOFType to JSX traversalMethods (#415)
Browse files Browse the repository at this point in the history
  • Loading branch information
j13huang committed Jul 20, 2022
1 parent adef04b commit 514f8c3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
19 changes: 19 additions & 0 deletions src/collections/JSXElement.js
Expand Up @@ -171,6 +171,25 @@ const traversalMethods = {
});
return Collection.fromPaths(paths, this, JSXElement);
},

/**
* Returns all children that are of jsxElementType.
*
* @return {Collection<jsxElementType>}
*/
childNodesOfType: function(jsxChildElementType) {
const paths = [];
this.forEach(function(path) {
const children = path.get('children');
const l = children.value.length;
for (let i = 0; i < l; i++) {
if (jsxChildElementType.check(children.value[i])) {
paths.push(children.get(i));
}
}
});
return Collection.fromPaths(paths, this, jsxChildElementType);
},
};

const mappingMethods = {
Expand Down
13 changes: 12 additions & 1 deletion src/collections/__tests__/JSXElement-test.js
Expand Up @@ -37,6 +37,7 @@ describe('JSXCollection API', function() {
' <Baz.Bar />',
' </Child>',
' <Child id="2" foo="baz" baz/>',
' {"foo"}',
'</FooBar>'
].join('\n'), {parser: getParser()}).program];
});
Expand Down Expand Up @@ -65,7 +66,7 @@ describe('JSXCollection API', function() {
Collection.fromNodes(nodes)
.findJSXElements('FooBar')
.childNodes();
expect(children.length).toBe(5);
expect(children.length).toBe(7);
expect(children.getTypes()).toContain('Expression');
});

Expand All @@ -79,6 +80,16 @@ describe('JSXCollection API', function() {
expect(children.getTypes()).toContain('JSXElement');
});

it('returns the child element types of an JSXElement', function() {
const children =
Collection.fromNodes(nodes)
.findJSXElements('FooBar')
.childNodesOfType(types.JSXExpressionContainer);

expect(children.length).toBe(1);
expect(children.getTypes()).toContain('JSXExpressionContainer');
});

it('returns a properly typed collection even if empty', function() {
const children =
Collection.fromNodes([])
Expand Down

0 comments on commit 514f8c3

Please sign in to comment.