我有一个数据结构,它基本上是嵌套列表/字典的混合:
class System:
def __init__(self, name, subsystems, uri):
self.name = name
self.subsystems = subsystems
self.uri = uri
A = System("A", [], "http://A")
B1 = System("B1", [], "http://B/B1")
B21 = System("B12", [], "http://B/B2/B21")
B22 = System("B22", [], "http://B/B2/B22")
B2 = System("B2", [B21, B22], "http://B/B2")
B = System("B", [B1, B2], "http://B")
C1 = System("C1", [], "http://C/C1")
C = System("C", [C1], "http://C")
S = System("S", [A, B, C], None)
在Python中,我编写了以下递归生成器:
def find_subsystem(system, name):
if system.name == name:
yield system.uri
for sub in system.subsystems:
yield from find_subsystem(sub, name)
允许我像
那样进行“查询”next(find_subsystem(S, "B22"))
#=> 'http://B/B2/B21'
或
list(find_subsystem(S, "B22"))
#=> ['http://B/B2/B21', 'http://B/B2/B22']
我想知道如何才能最好地在JavaScript中编写一个等价物:我知道我可以用yield
做一些事情,但我认为由于yield from
,Python代码非常干净。是用JavaScript还是常用成语?
(我可以猜测使用来自underscore.js
的东西,但我想“手动”做这个练习)
答案 0 :(得分:0)
关注@vaultah评论后,我使用yield*
获得了以下解决方案:
function System(name, subsystems, uri) {
this.name = name;
this.subsystems = subsystems;
this.uri = uri;
}
var A = new System("A", [], "http://A");
var B1 = new System("B1", [], "http://B/B1");
var B21 = new System("B21", [], "http://B/B2/B21");
var B22 = new System("B22", [], "http://B/B2/B22");
var B2 = new System("B2", [B21, B22], "http://B/B2");
var B = new System("B", [B1, B2], "http://B");
var C1 = new System("C1", [], "http://C/C1");
var C = new System("C", [C1], "http://C/");
var S = new System("S", [A, B, C], "");
function* find_subsystem(system, name) {
if(system.name == name) {
yield system.uri;
}
for (var i = 0; i < system.subsystems.length; i++) {
yield* find_subsystem(system.subsystems[i], name);
}
}
console.log(find_subsystem(S, "B22").next().value);