| 1 |
"use strict"; |
| 2 |
module.exports = FilteredElementList; |
| 3 |
|
| 4 |
var Node = require('./Node'); |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 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 |
|
| 35 |
|
| 36 |
|
| 37 |
this.traverse(); |
| 38 |
} |
| 39 |
return this.cache[n]; |
| 40 |
} }, |
| 41 |
|
| 42 |
checkcache: { value: function() { |
| 43 |
if (this.lastModTime !== this.root.lastModTime) { |
| 44 |
|
| 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 |
|
| 55 |
|
| 56 |
|
| 57 |
traverse: { value: function(n) { |
| 58 |
|
| 59 |
if (n !== undefined) n++; |
| 60 |
|
| 61 |
var elt; |
| 62 |
while ((elt = this.next()) !== null) { |
| 63 |
this[this.cache.length] = elt; |
| 64 |
this.cache.push(elt); |
| 65 |
if (n && this.cache.length === n) return; |
| 66 |
} |
| 67 |
|
| 68 |
|
| 69 |
this.done = true; |
| 70 |
} }, |
| 71 |
|
| 72 |
|
| 73 |
next: { value: function() { |
| 74 |
var start = (this.cache.length === 0) ? this.root |
| 75 |
: this.cache[this.cache.length-1]; |
| 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 |
}); |