[英]DFS implemtation on an Array of objects in Typescript/JavaScript
I have a Class containing keys, values and children like this 我有一个包含键,值和此类子项的类
class Container{
key: string,
value: string,
children: Container[]
}
function searchKey(container: Container, key:string){
if (container.key == key) {
return container;
}
else if (container.children.length>0){
for (let child of container.children) {
let found = searchKey(child, key);
if (found != null) {
return found;
}
}
}
return null;
}
Input which I will be supplying to searchKey() function would be an array with deep objects and I want to get value for the supplied key parameter. 我将提供给searchKey()函数的输入将是一个具有深层对象的数组,我想获取所提供的key参数的值。 But the current searchKey() function would not accept an array. 但是当前的searchKey()函数将不接受数组。 How to make it to work with an array as input? 如何使其与数组作为输入一起使用?
Your searchKey()
function currently accepts a single Container
and checks it for a match against key
. 您的searchKey()
函数当前接受单个Container
并检查它是否与key
匹配。 If it fails, it iterates through the children
array of Container
s and calls itself recursively on each one. 如果失败,它将遍历Container
的children
级数组,并在每个数组上递归调用自身。
If you only intend to call the function with an array of Container
and never need to pass in a single Container
, then you can turn the function inside-out like this: 如果只打算用一个Container
数组调用该函数,而无需传递单个Container
,则可以像下面这样将函数由内向外翻转:
function searchKey(containers: Container[], key: string): Container | null {
if (containers.length > 0) {
for (let container of containers) {
if (container.key == key) {
return container;
} else {
let found = searchKey(container.children, key);
if (found != null) {
return found;
}
}
}
}
return null;
}
(I tried to keep the above function in the same style as your original.) (我试图使上述功能保持与原来的样式相同。)
This searchKey()
function starts off by iterating through an array of Container
s. 这个searchKey()
函数通过遍历Container
的数组开始。 It checks each Container
for a key
match, and if it doesn't find it, it calls itself recursively on the children
array. 它检查每个Container
是否有key
匹配,如果找不到,则在children
数组上递归调用自身。
There are other ways of doing this, of course. 当然,还有其他方法可以做到这一点。 Examples: 例子:
Container | Container[]
一个接受Container | Container[]
双重功能 Container | Container[]
arguments; Container | Container[]
参数; searchKey()
with a dummy Container
object whose children
is the array you want. 一个简单的填充程序,它使用一个虚拟Container
对象调用您现有的searchKey()
,该对象的children
是您想要的数组。 Which one is best depends on your use case. 哪一个最好取决于您的用例。
Hope that helps; 希望能有所帮助; good luck. 祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.