Last active
August 29, 2015 14:17
-
-
Save bananaumai/164b24b264e0f917007c to your computer and use it in GitHub Desktop.
JSでLinked Listのイメージ。大きなサイズのリストでforEach等のtraversableなメソッドを実行するとstack overflowする。
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
'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