Skip to content

Instantly share code, notes, and snippets.

@shovon
Created April 8, 2019 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shovon/b774ab895dcda650563cade2832596d0 to your computer and use it in GitHub Desktop.
Save shovon/b774ab895dcda650563cade2832596d0 to your computer and use it in GitHub Desktop.

Linked List with Iterator

An example of flattening a linked list with generators.

Usage

const LinkedList = require('./linked-list');

const list = new LinkedList();

list.push(10);
list.push('foo');
list.push('bar');
list.push(42);

console.log([...list]);
// [ 10, 'foo', 'bar', 42 ]
class Node {
constructor(value, next = null) {
this.value = value;
this.next = next;
}
*[Symbol.iterator]() {
yield this.value;
if (this.next !== null) { yield * this.next; }
}
}
module.exports = class LinkedList {
constructor() { this.head = null; }
push(value) {
this.head = new Node(value, this.head);
}
peek() {
if (this.head === null) { return null; }
return this.head.value;
}
pop() {
const old = this.head;
this.head = this.head.next;
return old.value;
}
*[Symbol.iterator]() {
if (this.head !== null) { yield * this.head; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment