Skip to content

Commit 514f8c3

Browse files
authored
add childNodesOFType to JSX traversalMethods (#415)
1 parent adef04b commit 514f8c3

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

src/collections/JSXElement.js

+19
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,25 @@ const traversalMethods = {
171171
});
172172
return Collection.fromPaths(paths, this, JSXElement);
173173
},
174+
175+
/**
176+
* Returns all children that are of jsxElementType.
177+
*
178+
* @return {Collection<jsxElementType>}
179+
*/
180+
childNodesOfType: function(jsxChildElementType) {
181+
const paths = [];
182+
this.forEach(function(path) {
183+
const children = path.get('children');
184+
const l = children.value.length;
185+
for (let i = 0; i < l; i++) {
186+
if (jsxChildElementType.check(children.value[i])) {
187+
paths.push(children.get(i));
188+
}
189+
}
190+
});
191+
return Collection.fromPaths(paths, this, jsxChildElementType);
192+
},
174193
};
175194

176195
const mappingMethods = {

src/collections/__tests__/JSXElement-test.js

+12-1
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ describe('JSXCollection API', function() {
3737
' <Baz.Bar />',
3838
' </Child>',
3939
' <Child id="2" foo="baz" baz/>',
40+
' {"foo"}',
4041
'</FooBar>'
4142
].join('\n'), {parser: getParser()}).program];
4243
});
@@ -65,7 +66,7 @@ describe('JSXCollection API', function() {
6566
Collection.fromNodes(nodes)
6667
.findJSXElements('FooBar')
6768
.childNodes();
68-
expect(children.length).toBe(5);
69+
expect(children.length).toBe(7);
6970
expect(children.getTypes()).toContain('Expression');
7071
});
7172

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

83+
it('returns the child element types of an JSXElement', function() {
84+
const children =
85+
Collection.fromNodes(nodes)
86+
.findJSXElements('FooBar')
87+
.childNodesOfType(types.JSXExpressionContainer);
88+
89+
expect(children.length).toBe(1);
90+
expect(children.getTypes()).toContain('JSXExpressionContainer');
91+
});
92+
8293
it('returns a properly typed collection even if empty', function() {
8394
const children =
8495
Collection.fromNodes([])

0 commit comments

Comments
 (0)