Skip to content

Commit 8a47fa2

Browse files
committed
refractor code and optimize loop
1 parent 9d11932 commit 8a47fa2

File tree

1 file changed

+24
-16
lines changed

1 file changed

+24
-16
lines changed

src/beautifulparser.nim

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,32 +7,40 @@ export xmltree
77
export options
88

99

10+
proc matches(child: XmlNode, options: Table[string, string]): bool =
11+
## Check if the child node matches the given options.
12+
for k, v in options.pairs():
13+
if not (child.attrs.hasKey(k) and child.attrs[k] == v):
14+
return false
15+
return true
16+
17+
1018
proc getNodes(node: XmlNode, name: string, options: Table[string, string]): seq[XmlNode] =
1119
## Find all child nodes with the given name and attributes matching the options.
20+
if len(options) == 0:
21+
return node.findAll(name)
22+
1223
for childr in node.findAll(name):
13-
if len(options) == 0:
14-
result.add(childr)
15-
continue
16-
elif childr.attrsLen == 0:
24+
if childr.attrsLen == 0:
1725
continue
18-
block iterOptions:
19-
for k, v in options.pairs():
20-
if not (childr.attrs.hasKey(k) and childr.attrs[k] == v):
21-
break iterOptions
26+
if matches(childr, options):
2227
result.add(childr)
2328

2429

2530
proc getNode(node: XmlNode, name: string, options: Table[string, string]): Option[XmlNode] =
2631
## Find the first child node with the given name and attributes matching the options.
27-
for childr in node.findAll(name):
28-
if len(options) == 0:
29-
return some(childr)
30-
elif childr.attrsLen == 0:
32+
let nodes = node.findAll(name)
33+
34+
if len(nodes) == 0:
35+
return none(XmlNode)
36+
37+
if len(options) == 0:
38+
return some(nodes[0])
39+
40+
for childr in nodes:
41+
if childr.attrsLen == 0:
3142
continue
32-
block iterOptions:
33-
for k, v in options.pairs():
34-
if not (childr.attrs.hasKey(k) and childr.attrs[k] == v):
35-
break iterOptions
43+
if matches(childr, options):
3644
return some(childr)
3745

3846

0 commit comments

Comments
 (0)