Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Forked from anonymous/linked-list.js
Last active December 31, 2015 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gordonbrander/8008868 to your computer and use it in GitHub Desktop.
Save gordonbrander/8008868 to your computer and use it in GitHub Desktop.
// https://en.wikipedia.org/wiki/Linked_list
// https://blog.jcoglan.com/2007/07/23/writing-a-linked-list-in-javascript/
// Reducible prototype for linked list node.
var __node__ = {
reduce: function reduceNodes(reducer, initial) {
var node = this;
var accumulated = initial;
do {
accumulated = reducer(accumulated, node);
node = next(node);
}
while(node !== null);
return accumulated;
}
};
// Create a linked list node.
function node(value, nextNode) {
// Create new node object.
var n = Object.create(__node__);
// Assign value and next.
n.value = value;
n.next = nextNode;
return n;
}
function next(node) {
return node && node.next ? node.next : null;
}
function value(node) {
return node && node.value ? node.value : null;
}
// Given 2 items, return second.
function chooseCurr(prev, curr) {
return curr;
}
// Find head of reducible data structure.
function head(reducible) {
return reducible.reduce(chooseCurr);
}
// Find first matching node for `predicate` in reducible
// data structure.
function find(reducible, predicate) {
return reducible.reduce(function reduceFind(found, node) {
// Match values, not nodes. This allows for general-purpose
// predicate functions.
if (found) return found;
if (predicate(value(node))) return node;
return null;
}, null);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment