Allow for finding multiple matching nodes.
Showing
1 changed file
with
12 additions
and
7 deletions
... | @@ -396,24 +396,29 @@ export const parseHtml = (html: string, options): NodeType => { | ... | @@ -396,24 +396,29 @@ export const parseHtml = (html: string, options): NodeType => { |
396 | return proxyNode(cached, options) | 396 | return proxyNode(cached, options) |
397 | } | 397 | } |
398 | 398 | ||
399 | export const findNode = (doc: NodeType, selector: string): NodeType => { | 399 | export const findNode = (doc: NodeType, selector: string, options = { single: true }): NodeType => { |
400 | if (!selector) return doc | 400 | if (!selector) return doc |
401 | let docCache = findNodeCache.get(doc) | 401 | let docCache = findNodeCache.get(doc) |
402 | if (!docCache) { | 402 | if (!docCache) { |
403 | docCache = new TTLCache({ ttl: 10*60 }) | 403 | docCache = new TTLCache({ ttl: 10*60 }) |
404 | findNodeCache.set(doc, docCache) | 404 | findNodeCache.set(doc, docCache) |
405 | } | 405 | } |
406 | const found = docCache.get(selector) | 406 | let found = docCache.get(selector) |
407 | if (found !== undefined) return found[0] | 407 | if (found === undefined) { |
408 | //console.log('cache miss', {selector}) | ||
409 | const matcher = createMatcher(selector) | 408 | const matcher = createMatcher(selector) |
409 | found = [] | ||
410 | try { | 410 | try { |
411 | walkSync(doc, (node, parent, index) => { | 411 | walkSync(doc, (node, parent, index) => { |
412 | if (matcher(node, parent, index)) throw node | 412 | if (node && node.type !== ELEMENT_NODE) return |
413 | if (matcher(node, parent, index)) { | ||
414 | found.push(node) | ||
415 | if (options.single) throw node | ||
416 | } | ||
413 | }) | 417 | }) |
414 | } catch (e) { | 418 | } catch (e) { |
415 | if (e instanceof Error) throw e | 419 | if (e instanceof Error) throw e |
416 | docCache.set(selector, [ e ]) | ||
417 | return e | ||
418 | } | 420 | } |
421 | docCache.set(selector, found) | ||
422 | } | ||
423 | return options.single ? found[ 0 ] : found | ||
419 | } | 424 | } | ... | ... |
-
Please register or sign in to post a comment