Skip to content

Instantly share code, notes, and snippets.

@arihantverma
Created August 21, 2024 17:36
Show Gist options
  • Save arihantverma/00213d928f944a662e547987f40e4a7b to your computer and use it in GitHub Desktop.
Save arihantverma/00213d928f944a662e547987f40e4a7b to your computer and use it in GitHub Desktop.
class LinkedList<T> {
value: T;
rest: LinkedList<T> | null;
constructor(value: T, rest: LinkedList<T> | null) {
this.value = value;
this.rest = rest;
}
get length(): number {
return 1 + (this.rest ? this.rest.length : 0);
}
static fromArray<T>(array: T[]): LinkedList<T> | null {
let result: LinkedList<T> | null = null;
for (let i = array.length - 1; i >= 0; i--) {
result = new this(array[i], result);
}
return result;
}
linkedListForIteration: LinkedList<T> | null = this;
[Symbol.iterator](): Iterator<T> {
const _this = this;
return {
next(): IteratorResult<T> {
if (_this.linkedListForIteration === null) {
return { value: undefined, done: true };
}
const valueToReturn = _this.linkedListForIteration.value;
_this.linkedListForIteration = _this.linkedListForIteration.rest;
return { value: valueToReturn, done: false };
},
};
}
}
const linkedList = LinkedList.fromArray([1, 2, 3, 4, 5]);
// for (const value of linkedList) {
// console.log(value)
// }
// const iterator = linkedList[Symbol.iterator]();
// console.info(iterator.next()); // { value: 1, done: false }
// console.info(iterator.next()); // { value: 2, done: false }
// console.info(iterator.next()); // { value: 3, done: false }
// console.info(iterator.next()); // { value: 4, done: false }
// console.info(iterator.next()); // { value: 5, done: false }
// console.info(iterator.next()); // { value: undefined, done: true }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment