Skip to content

Instantly share code, notes, and snippets.

@bananaumai
Last active August 29, 2015 14:17
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 bananaumai/164b24b264e0f917007c to your computer and use it in GitHub Desktop.
Save bananaumai/164b24b264e0f917007c to your computer and use it in GitHub Desktop.
JSでLinked Listのイメージ。大きなサイズのリストでforEach等のtraversableなメソッドを実行するとstack overflowする。
'use strict';
var LinkedList = {};
LinkedList.prototype = {
head: function() {
return this._head;
},
tail: function() {
return this._tail;
},
push: function(val) {
return new NonEmptyList(val, this);
},
forEach: function(fnc) {
fnc(this._head);
if (this._tail instanceof NonEmptyList) {
this._tail.forEach(fnc);
}
}
};
var EmptyList = function() {
this._head = null;
this._tail = null;
};
EmptyList.prototype = Object.create(LinkedList.prototype);
EmptyList.prototype.constructor = EmptyList;
var NonEmptyList = function(head, tail) {
this._head = head;
this._tail = tail;
};
NonEmptyList.prototype = Object.create(LinkedList.prototype);
NonEmptyList.prototype.constructor = NonEmptyList;
LinkedList.of = function() {
var _create = function(vals, list) {
if (vals.length === 0) return list;
var head = vals.shift();
return _create(vals, new NonEmptyList(head, list))
};
return _create(
Array.prototype.slice.call(arguments).reverse(),
new EmptyList()
);
};
var list = LinkedList.of();
for (var i = 0; i < 100000; i++) {
list = list.push(i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment