jsclass
jsclass copied to clipboard
Request: add a method for converting a linked list to a string
While debugging linked lists, it could be useful to have a function that converts the list to a string representing the elements. Here is a function I use now:
LinkedList.Doubly.Circular.prototype.toString = function() {
var s = "";
this.forEach(function(node, i) {
var sfield = "";
for (var field in node) {
if (node.hasOwnProperty(field) && field!='prev' && field !='next' && field !='list') {
if (sfield) sfield+=",";
sfield += field+":"+node[field];
}
}
if (s) s+=",\n ";
s +="{"+sfield+"}"
});
return "["+s+"]";
}
Example:
var list = new LinkedList.Doubly.Circular();
var foo = {f:1}, bar = {b:1}, baz = {z:1};
list.push(foo);
list.push(bar);
list.push(baz);
console.log(list.toString());
Result:
[{f:1}, {b:1}, {z:1}]
I believe it can be useful to others too.