Last active
August 29, 2015 14:04
-
-
Save alexanderGugel/b2beef1e2b5bb21f1e30 to your computer and use it in GitHub Desktop.
Linked List without a single if-statement? - Challenge accepted!
This file contains hidden or 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
// PoC: Implemented methods: addToTail(value), removeHead() #=> value, contains(value) #=> boolean | |
var tail = { | |
next: this, | |
removeHead: function () { | |
return null; | |
}, | |
contains: function (value) { | |
return false; | |
}, | |
addToTail: function (value) { | |
return new Node(value); | |
} | |
}; | |
var Node = function (value, next) { | |
this.value = value; | |
this.next = next || tail; | |
}; | |
Node.prototype.addToTail = function (value) { | |
this.next = this.next.addToTail(value); | |
return this; | |
}; | |
Node.prototype.contains = function (value) { | |
// Ok, condition... | |
return this.value === value ? true : this.next.contains(value); | |
}; | |
var LinkedList = function () { | |
this.head = tail; | |
}; | |
LinkedList.prototype.addToTail = function (value) { | |
this.head = this.head.addToTail(value); | |
}; | |
LinkedList.prototype.removeHead = function () { | |
var oldHead = this.head; | |
this.head = oldHead.next; | |
return oldHead.value; | |
}; | |
LinkedList.prototype.contains = function (value) { | |
return this.head.contains(value); | |
}; | |
//// Example: | |
var linkedList = new LinkedList(); | |
linkedList.addToTail(1); | |
linkedList.addToTail(2); | |
linkedList.addToTail(3); | |
console.log('true!', linkedList.contains(1)); | |
console.log('true!', linkedList.contains(2)); | |
console.log('true!', linkedList.contains(3)); | |
console.log('1!', linkedList.removeHead()); | |
console.log('false!', linkedList.contains(1)); | |
console.log('true!', linkedList.contains(2)); | |
console.log('true!', linkedList.contains(3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment