Skip to content

Commit 84f159f

Browse files
committed
generic-utils: cache the get
1 parent 9720ff4 commit 84f159f

File tree

1 file changed

+24
-10
lines changed

1 file changed

+24
-10
lines changed

src/WABinary/generic-utils.ts

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,32 @@ import { type BinaryNode } from './types'
44

55
// some extra useful utilities
66

7+
const indexCache = new WeakMap<BinaryNode, Map<string, BinaryNode[]>>()
8+
79
export const getBinaryNodeChildren = (node: BinaryNode | undefined, childTag: string) => {
8-
if (Array.isArray(node?.content)) {
9-
return node.content.filter(item => item.tag === childTag)
10-
}
10+
if (!node || !Array.isArray(node.content)) return []
1111

12-
return []
12+
let index = indexCache.get(node)
13+
14+
// Build the index once per node
15+
if (!index) {
16+
index = new Map<string, BinaryNode[]>()
17+
18+
for (const child of node.content) {
19+
let arr = index.get(child.tag)
20+
if (!arr) index.set(child.tag, (arr = []))
21+
arr.push(child)
22+
}
23+
24+
indexCache.set(node, index)
25+
}
26+
27+
// Return first matching child
28+
return index.get(childTag)
29+
}
30+
31+
export const getBinaryNodeChild = (node: BinaryNode | undefined, childTag: string) => {
32+
return getBinaryNodeChildren(node, childTag)?.[0]
1333
}
1434

1535
export const getAllBinaryNodeChildren = ({ content }: BinaryNode) => {
@@ -20,12 +40,6 @@ export const getAllBinaryNodeChildren = ({ content }: BinaryNode) => {
2040
return []
2141
}
2242

23-
export const getBinaryNodeChild = (node: BinaryNode | undefined, childTag: string) => {
24-
if (Array.isArray(node?.content)) {
25-
return node?.content.find(item => item.tag === childTag)
26-
}
27-
}
28-
2943
export const getBinaryNodeChildBuffer = (node: BinaryNode | undefined, childTag: string) => {
3044
const child = getBinaryNodeChild(node, childTag)?.content
3145
if (Buffer.isBuffer(child) || child instanceof Uint8Array) {

0 commit comments

Comments
 (0)