Created
November 3, 2017 21:55
-
-
Save jtompkins/f26b08dc1cc90e45195b48457ae52bd3 to your computer and use it in GitHub Desktop.
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
class LinkedList { | |
static fromString(str) { | |
return [...str].reduce((acc, next) => acc.shift(next), new LinkedList()) | |
} | |
constructor(initial) { | |
this.head = initial ? new ListNode(initial) : null | |
} | |
shift(value) { | |
const node = new ListNode(value) | |
node.next = this.head | |
this.head = node | |
return this | |
} | |
*[Symbol.iterator]() { | |
let next = this.head | |
while (next != null) { | |
yield next | |
next = next.next | |
} | |
} | |
toString() { | |
return [...this].reverse().reduce((acc, next) => (acc += next), '') | |
} | |
toInt() { | |
return Number.parseInt(this.toString()) | |
} | |
add(ll) { | |
const sum = this.toInt() + ll.toInt() | |
return LinkedList.fromString(sum.toString()) | |
} | |
} | |
class ListNode { | |
constructor(value, next) { | |
this.value = value | |
this.next = next | |
} | |
toString() { | |
return this.value.toString() | |
} | |
} | |
const testLinkedList = (() => { | |
const left = LinkedList.fromString('123') | |
const right = LinkedList.fromString('123') | |
const result = left.add(right) | |
console.log(result.toInt()) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment