Skip to content

Request: add a method for converting a linked list to a string #39

Open
@erelsgl

Description

@erelsgl

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions