Last active
April 23, 2019 11:06
-
-
Save eczn/343f9320c68434f614e318efcaf348cb to your computer and use it in GitHub Desktop.
ListNode in TypeScript (a generic example)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class ListNode<T> { | |
val: T; | |
next: ListNode<T> | null; | |
constructor(val: T, next: ListNode<T> | null = null) { | |
this.val = val; | |
this.next = next; | |
} | |
/** | |
* make next of this to be `left` | |
* @param left | |
*/ | |
beNextOf(left: ListNode<T>) { | |
left.next = this; | |
return left; | |
} | |
/** | |
* create a `ListNode` from an array | |
* @param arr | |
*/ | |
static fromArray<ItemType>(arr: ItemType[]) { | |
const nodes = arr.map(item => new ListNode(item)); | |
return nodes.reduceRight((acc, cur) => { | |
return acc.beNextOf(cur); | |
}); | |
} | |
/** | |
* forEach a `ListNode` | |
* @param cb | |
*/ | |
forEach(cb: (item: T, idx: number) => void, idx = 0) { | |
cb(this.val, idx); | |
// recursive exec this.forEach when this.next is not null | |
this.next && this.next.forEach(cb, idx + 1); | |
} | |
} | |
// create a ListNode from an array | |
const n = ListNode.fromArray([1, 2, 3, 4]); | |
// forEach | |
n.forEach((val, idx) => { | |
console.log('val', val, 'idx', idx); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment