forked from ssitu001/toyProblemPractice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilterFamilyMembers.js
64 lines (55 loc) · 1.52 KB
/
filterFamilyMembers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//filterFamilyMembers.js
// `filterFamilyMembers` accepts two arguments, a family tree object, and a truth test. `filterFamilyMembers` returns an array, in any order, of the full names of family members who pass the passed in truth test. You will need to use recursion in your solution in order to handle nested familty trees.
// EXAMPLE:
var familyTree = {
'firstName': 'Simon',
'lastName': 'Smith',
'location': 'San Francisco',
'children': [
{
'firstName': 'Bob',
'lastName': 'Smith',
'location': 'San Francisco',
'children': [
{
'firstName': 'Sam',
'lastName': 'Smith',
'location': 'Tokyo',
'children': []
}
]
},
{
'firstName': 'Stacy',
'lastName': 'Williams',
'location': 'San Francisco',
'children': [
{
'firstName': 'Sean',
'lastName': 'Williams',
'location': 'San Francisco',
'children': []
}
]
}
]
};
var livesInSF = function (familyMember) {
return familyMember.location === 'San Francisco';
}
var filterFamilyMembers = function (tree, truthTest) {
var result = [];
var inner = function(trees, truthTests) {
if (truthTests(trees)) {
result.push(trees.firstName + ' ' + trees.lastName);
}
if (trees.children.length) {
for(var i = 0; i < trees.children.length; i++) {
inner(trees.children[i], truthTest);
}
}
};
inner(tree, truthTest);
return result;
};
filterFamilyMembers(familyTree, livesInSF);