composite pattern

Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

by bhupendra negi

HTML

<p>composite pattern</p>
<input type="button" value="Run Composite Pattern" onclick="run()" />

JavaScript

var Node = function (name) {
    this.children = [];
    this.name = name;
}

Node.prototype = {
    add: function (child) {
        this.children.push(child);
    },

    remove: function (child) {
        var length = this.children.length;
        for (var i = 0; i < length; i++) {
            if (this.children[i] === child) {
                this.children.splice(i, 1);
                return;
            }
        }
    },

    setWeight: function (w) {
        this.weight = w;
    },

    getChild: function (i) {
        return this.children[i];
    },

    hasChildren: function () {
        return this.children.length > 0;
    },
    getWeight : function () {
        var length = this.children.length;
        console.log("lenght =>"+length);
        console.log(this);
        var sum = 0;
        for (var i = 0; i < length; i++) {
            sum += this.children[i].weight;

        }
        return sum;

    }
}

// recursively traverse a (sub)tree

function traverse(indent, node) {
    log.add(Array(indent++).join("--") + node.name);

    for (var i = 0, len = node.children.length; i < len; i++) {
        traverse(indent, node.getChild(i));
    }
}

// logging helper

var log = (function () {
    var log = "";

    return {
        add: function (msg) {
            log += msg + "\n";
        },
        show: function () {
            alert(log);
            log = "";
        }
    }
})();

function run() {
    var tree = new Node("root");
    var left = new Node("left");
    left.setWeight(10);
    var right = new Node("right");
    right.setWeight(20);

    console.log(right);
    console.log(tree);

    var leftleft = new Node("leftleft");
    var leftright = new Node("leftright");
    var rightleft = new Node("rightleft");
    var rightright = new Node("rightright");

    tree.add(left);
    tree.add(right);
    tree.remove(right); // note: remove
    tree.add(right);

    left.add(leftleft);
    left.add(leftright);

    right.add(rightleft);
   ...