Skip to content

Instantly share code, notes, and snippets.

@kjlape
Created March 5, 2018 12:46
Show Gist options
  • Select an option

  • Save kjlape/7ca3b050c019a6b8a334dcbcda580766 to your computer and use it in GitHub Desktop.

Select an option

Save kjlape/7ca3b050c019a6b8a334dcbcda580766 to your computer and use it in GitHub Desktop.
Linked List in JS
function Node(data, { left, right } = {}) {
this.data = data
this._left = left || this,
this._right = right || this
}
Node.prototype = {
left,
right,
insertLeft,
insertRight,
remove,
toArray
}
function left() {
return this._left
}
function right() {
return this._right
}
function insertLeft(data) {
const left = new Node(data, { left: this.left(), right: this })
this._left._right = left
return this._left = left
}
function insertRight(data) {
const right = new Node(data, { left: this, right: this.right() })
this._right._left = right
return this._right = right
}
function remove() {
this._left._right = this._right
this._right._left = this._left
return this
}
function toArray(direction = 'right') {
const array = [this.data]
let node = this
while (this !== (node = node[direction]())) {
array.push(node.data)
}
return array
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment