Skip to content

Instantly share code, notes, and snippets.

@humoyun
Created May 12, 2022 05:48
Show Gist options
  • Save humoyun/1bbdb4b36300c350e0c63db73b82fbcb to your computer and use it in GitHub Desktop.
Save humoyun/1bbdb4b36300c350e0c63db73b82fbcb to your computer and use it in GitHub Desktop.
JavaScriptda ES6 iterator va generatorlar bilan ishlashga misollar
// DOM traversal
const parent = document.createElement("div");
parent.innerHTML = `
<div id="subTree">
<form>
<input type="text"/>
</form>
<p>Paragraph</p>
<span>Span</span>
</div>
`;
const subTree = parent;
// recursive solution
const traverseDOMRecursive = function (elem, cb) {
cb(elem);
elem = elem.firstElementChild;
while (elem) {
traverseDOMRecursive(elem, cb);
elem = elem.nextElementSibling;
}
};
function callback(element) {
console.assert(element !== null, element.nodeName);
}
traverseDOMRecursive(subTree, callback);
// solution with generators
const traverseDOMGenerator = function* (elem) {
yield elem;
elem = elem.firstElementChild;
while (elem) {
yield* traverseDOMGenerator(elem);
elem = elem.nextElementSibling;
}
};
for (let element of traverseDOMGenerator(subTree)) {
console.log("element", element.nodeName);
}
/**
* inspired by Python's built-in range utility function
* implemented using ES6 Iterable, Iterator protolols (interfaces)
*
* @author: Humoyun Ahmad
*/
class Range {
constructor(...args) {
this.start = args.length <= 1 ? 0 : args[0];
this.end = args.length <= 1 ? args[0] || 0 : args[1];
this.step = args.length <= 2 ? 1 : args[2];
}
[Symbol.iterator]() {
return this;
}
next() {
if (this.end > this.start) {
const result = { done: false, value: this.start };
this.start = this.start + this.step;
return result;
} else return { done: true, value: undefined };
}
}
/**
* Symbol.iterator is part of the couple of inbuilt symbols
* available in JavaScript. It allows for hooking into the
* inbuilt for of iteration mechanism. This is why the
* Symbol.iterator comes into play when talking about
* iterables and iterators in JavaScript.
*/
function range(...args) {
return new Range(...args);
}
console.log([...range(4)]);
console.log([...range(2, 5)]);
console.log([...range(1, 10, 3)]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment