Created
December 17, 2013 17:23
-
-
Save anonymous/8008857 to your computer and use it in GitHub Desktop.
Simple linked list
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
// https://en.wikipedia.org/wiki/Linked_list | |
// https://blog.jcoglan.com/2007/07/23/writing-a-linked-list-in-javascript/ | |
// Create a node in a linked list. | |
function node(value, nextNode) { | |
return { value: value, next: nextNode }; | |
} | |
function next(node) { | |
return node && node.next ? node.next : null; | |
} | |
function value(node) { | |
return node && node.value ? node.value : null; | |
} | |
function find(node, predicate) { | |
// Capture variable to avoid mutating closure variable. | |
var n = node; | |
while(next(n) !== null && !predicate(value(n))) n = next(n); | |
return n; | |
} | |
function head(node) { | |
// Capture variable to avoid mutating closure variable. | |
var n = node; | |
while(next(n) !== null) n = next(n); | |
return n; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment