Skip to content

Instantly share code, notes, and snippets.

@huttj
Created August 11, 2019 20:07
Show Gist options
  • Save huttj/99ed0221fc6f4f51f22bf59218a049cc to your computer and use it in GitHub Desktop.
Save huttj/99ed0221fc6f4f51f22bf59218a049cc to your computer and use it in GitHub Desktop.
Just playing around with iterators
class LinkedList {
constructor(value) {
this.value = value;
this.next = null;
}
push(value) {
let end = this;
while (end.next) {
end = end.next;
}
end.next = new LinkedList(value);
}
map(fn) {
let i = 0;
let head;
let cur;
for (const value of this) {
const result = new LinkedList(fn(value, i));
if (!head) {
head = result;
cur = head;
} else {
cur.next = result;
cur = cur.next;
}
}
return head;
}
}
LinkedList.fromArray = (array) => {
let head = new LinkedList(array[0]);
curr = head;
for (let i = 1; i < array.length; i++) {
curr.next = new LinkedList(array[i]);
curr = curr.next;
}
return head;
};
LinkedList.prototype[Symbol.iterator] = function* () {
let head = this;
yield head.value;
while (head = head.next) {
yield head.value;
}
};
// const list = LinkedList.fromArray([1,2,3,4,5]).map(n => `${n} * ${n} = ${n*n}`);
//
// for (const value of list) {
// console.log(value);
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment