Skip to content

Instantly share code, notes, and snippets.

@skiano
Last active September 28, 2018 02:46
Show Gist options
  • Save skiano/bd359cbd9eb6fe63fe8bef48dd62cb85 to your computer and use it in GitHub Desktop.
Save skiano/bd359cbd9eb6fe63fe8bef48dd62cb85 to your computer and use it in GitHub Desktop.
little doubly linked list
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;
}
}
}
@skiano
Copy link
Author

skiano commented Sep 28, 2018

// 485 bytes
function createList(){var n,t,r,f="prev",e="next",i=0;return{length:function(){return i},head:function(){return n},tail:function(){return t},add:function(o){r={v:o},t&&(t[f]=r,r[e]=t),n||(n=r),t=r,i+=1},remove:function(o){if(r=o||t,i&&r){const o=r[e],u=r[f];o?o[f]=u:n=u,u?u[e]=o:t=o,i-=1}},walk:function(t,e){for(r=e||n;r;)t(r),r=r[f]},walkBack:function(n,f){for(r=f||t;r;)n(r),r=r[e]},find:function(t){if(r=n,+t<0)for(;r;){if(t(r))return r;r=r[f]}else for(;r&&t--;)r=r[f];return r}}}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment