Debian Codegraph @

mixmark-io-domino/lib/FilteredElementList.js

raw symbols SCIP
1 "use strict";
2 module.exports = FilteredElementList;
3
4 var Node = require('./Node');
5
6 //
7 // This file defines node list implementation that lazily traverses
8 // the document tree (or a subtree rooted at any element) and includes
9 // only those elements for which a specified filter function returns true.
10 // It is used to implement the
11 // {Document,Element}.getElementsBy{TagName,ClassName}{,NS} methods.
12 //
13 // XXX this should inherit from NodeList
14
15 function FilteredElementList(root, filter) {
16 this.root = root;
17 this.filter = filter;
18 this.lastModTime = root.lastModTime;
19 this.done = false;
20 this.cache = [];
21 this.traverse();
22 }
23
24 FilteredElementList.prototype = Object.create(Object.prototype, {
25 length: { get: function() {
26 this.checkcache();
27 if (!this.done) this.traverse();
28 return this.cache.length;
29 } },
30
31 item: { value: function(n) {
32 this.checkcache();
33 if (!this.done && n >= this.cache.length) {
34 // This can lead to O(N^2) behavior if we stop when we get to n
35 // and the caller is iterating through the items in order; so
36 // be sure to do the full traverse here.
37 this.traverse(/*n*/);
38 }
39 return this.cache[n];
40 } },
41
42 checkcache: { value: function() {
43 if (this.lastModTime !== this.root.lastModTime) {
44 // subtree has changed, so invalidate cache
45 for (var i = this.cache.length-1; i>=0; i--) {
46 this[i] = undefined;
47 }
48 this.cache.length = 0;
49 this.done = false;
50 this.lastModTime = this.root.lastModTime;
51 }
52 } },
53
54 // If n is specified, then traverse the tree until we've found the nth
55 // item (or until we've found all items). If n is not specified,
56 // traverse until we've found all items.
57 traverse: { value: function(n) {
58 // increment n so we can compare to length, and so it is never falsy
59 if (n !== undefined) n++;
60
61 var elt;
62 while ((elt = this.next()) !== null) {
63 this[this.cache.length] = elt; //XXX Use proxy instead
64 this.cache.push(elt);
65 if (n && this.cache.length === n) return;
66 }
67
68 // no next element, so we've found everything
69 this.done = true;
70 } },
71
72 // Return the next element under root that matches filter
73 next: { value: function() {
74 var start = (this.cache.length === 0) ? this.root // Start at the root or at
75 : this.cache[this.cache.length-1]; // the last element we found
76
77 var elt;
78 if (start.nodeType === Node.DOCUMENT_NODE)
79 elt = start.documentElement;
80 else
81 elt = start.nextElement(this.root);
82
83 while(elt) {
84 if (this.filter(elt)) {
85 return elt;
86 }
87
88 elt = elt.nextElement(this.root);
89 }
90 return null;
91 } },
92 });