-
-
Save gordonbrander/8008868 to your computer and use it in GitHub Desktop.
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
// 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