Convert the nodeProxyHandler to a class.
Showing
1 changed file
with
16 additions
and
10 deletions
... | @@ -307,34 +307,40 @@ export const createMatcher = (selector: string): Matcher => { | ... | @@ -307,34 +307,40 @@ export const createMatcher = (selector: string): Matcher => { |
307 | return newMatcherCreater() | 307 | return newMatcherCreater() |
308 | } | 308 | } |
309 | 309 | ||
310 | const nodeProxyHandler = { | 310 | class NodeProxyHandler { |
311 | #cache | ||
312 | constructor() { | ||
313 | this.#cache = {} | ||
314 | } | ||
315 | |||
311 | get(target, prop, receiver) { | 316 | get(target, prop, receiver) { |
312 | const { _proxy } = target | 317 | const { _proxy } = target |
313 | if (prop in _proxy) return _proxy[ prop ] | 318 | if (prop in this.#cache) return this.#cache[ prop ] |
314 | const { [ prop ]: origValue } = target | 319 | const { [ prop ]: origValue } = target |
315 | if (!origValue) return origValue | 320 | if (!origValue) return origValue |
316 | switch (prop) { | 321 | switch (prop) { |
317 | case 'attributes': | 322 | case 'attributes': |
318 | return _proxy[ prop ] = (origValue ? Object.fromEntries(Object.entries(origValue).map(([ key, value ]) => { | 323 | return this.#cache[ prop ] = (origValue ? Object.fromEntries(Object.entries(origValue).map(([ key, value ]) => { |
319 | return [ key, decode(value) ] | 324 | return [ key, decode(value) ] |
320 | })) : origValue) | 325 | })) : origValue) |
321 | return newValue | 326 | return newValue |
322 | case 'parent': | 327 | case 'parent': |
323 | return _proxy[ prop ] = proxyNode(origValue) | 328 | return this.#cache[ prop ] = proxyNode(origValue) |
324 | case 'children': | 329 | case 'children': |
325 | return _proxy[ prop ] = origValue.map((child) => proxyNode(child)) | 330 | return this.#cache[ prop ] = origValue.map((child) => proxyNode(child)) |
326 | default: | 331 | default: |
332 | if (typeof origValue === 'function') { | ||
333 | return this.#cache[ prop ] = (...args) => { | ||
334 | origValue.apply(target, ...args) | ||
335 | } | ||
336 | } | ||
327 | return origValue | 337 | return origValue |
328 | } | 338 | } |
329 | } | 339 | } |
330 | } | 340 | } |
331 | 341 | ||
332 | const proxyNode = (node) => { | 342 | const proxyNode = (node) => { |
333 | const { _proxy: { proxy } = {} } = node | 343 | return new Proxy(node, new NodeProxyHandler()) |
334 | if (proxy) return proxy | ||
335 | const newProxy = new Proxy(node, nodeProxyHandler) | ||
336 | node._proxy = { proxy: newProxy } | ||
337 | return newProxy | ||
338 | } | 344 | } |
339 | 345 | ||
340 | export const parseHtml = (html: string): NodeType => { | 346 | export const parseHtml = (html: string): NodeType => { | ... | ... |
-
Please register or sign in to post a comment