Skip to content

Instantly share code, notes, and snippets.

@eligrey
Last active May 8, 2024 21:23
Show Gist options
  • Select an option

  • Save eligrey/243712 to your computer and use it in GitHub Desktop.

Select an option

Save eligrey/243712 to your computer and use it in GitHub Desktop.
Iterator implementations for XPathResult
// Requires ECMAScript 6
"use strict";
XPathResult.prototype[Symbol.iterator] = function* () {
let node;
switch (this.resultType) {
case XPathResult.UNORDERED_NODE_ITERATOR_TYPE:
case XPathResult.ORDERED_NODE_ITERATOR_TYPE:
while (node = this.iterateNext()) {
yield node;
}
break;
case XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE:
case XPathResult.ORDERED_NODE_SNAPSHOT_TYPE:
for (const node = this.snapshotLength; i < node; i++) {
yield this.snapshotItem(node);
}
break;
}
};
// Requires JavaScript 1.7
/*jslint white: true, onevar: true, undef: true, nomen: true, eqeqeq: true, bitwise: true,
regexp: true, strict: true, newcap: true, immed: true, maxerr: 1000, maxlen: 90 */
/*global XPathResult, StopIteration */
"use strict";
XPathResult.prototype.__iterator__ = function (flag) {
var node, i = 0;
switch (this.resultType) {
case XPathResult.UNORDERED_NODE_ITERATOR_TYPE:
case XPathResult.ORDERED_NODE_ITERATOR_TYPE:
while (node = this.iterateNext()) {
i++;
yield flag ? i : node;
}
break;
case XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE:
case XPathResult.ORDERED_NODE_SNAPSHOT_TYPE:
for (node = this.snapshotLength; i < node; i++) {
yield flag ? i : this.snapshotItem(node);
}
break;
}
throw StopIteration;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment