Skip to content

Instantly share code, notes, and snippets.

Created December 17, 2013 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/8008857 to your computer and use it in GitHub Desktop.
Save anonymous/8008857 to your computer and use it in GitHub Desktop.
Simple linked list
// 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