Last active
September 28, 2018 02:46
-
-
Save skiano/bd359cbd9eb6fe63fe8bef48dd62cb85 to your computer and use it in GitHub Desktop.
little doubly 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
function createList() { | |
var next = 'prev' | |
, prev = 'next' | |
, length = 0 | |
, head | |
, tail | |
, arr | |
, n; | |
return { | |
length: function() { return length; }, | |
head: function() { return head; }, | |
tail: function() { return tail; }, | |
add: function(value) { | |
n = { v: value }; | |
if (tail) { | |
tail[next] = n; | |
n[prev] = tail; | |
} | |
if (!head) { | |
head = n; | |
} | |
tail = n; | |
length += 1; | |
}, | |
remove: function(node) { | |
n = node || tail; | |
if (length && n) { | |
const l = n[prev]; | |
const r = n[next]; | |
if (l) { | |
l[next] = r; | |
} else { | |
head = r; | |
} | |
if (r) { | |
r[prev] = l; | |
} else { | |
tail = l; | |
} | |
length -= 1; | |
} | |
}, | |
walk: function(cb, start) { | |
n = start || head; | |
while (n) { | |
cb(n); | |
n = n[next]; | |
} | |
}, | |
walkBack: function(cb, start) { | |
n = start || tail; | |
while (n) { | |
cb(n); | |
n = n[prev]; | |
} | |
}, | |
find: function(predicate) { | |
n = head; | |
if (+predicate < 0) { | |
while (n) { | |
if (predicate(n)) return n; | |
n = n[next]; | |
} | |
} else { | |
while (n && predicate--) { | |
n = n[next]; | |
} | |
} | |
return n; | |
} | |
} | |
} |
Author
skiano
commented
Sep 28, 2018
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment