javascriptarraysrowscellschained

Adding elements to array via chained functions calls


I have an array:

        var cells = [
            [1, 2, 3],
            [4, 5, 6],
            [7, 8, 9]
        ];

My javascript code parse this array and draw as a table.

Now i want add functions to simplify adding rows and cells to table, so i begin with this code:

Array.prototype.tsoAddRow = function () {
    this.push([]);
    return this[this.length-1];
};


Array.prototype.tsoAddCell = function (value) {
    this.push(value);
};

cells.tsoAddRow().tsoAddCell("123");

It works fine, result is Array [ Array[1] ] but i need more.

How i can improve this functions so i able use them ike this:

cells.tsoAddRow().tsoAddCell("1").tsoAddCell("2").tsoAddCell("3")
.tsoAddRow().tsoAddCell("4").tsoAddCell("5").tsoAddCell("6")
.tsoAddRow().tsoAddCell("7").tsoAddCell("8").tsoAddCell("9")

Or similar chained way. Tables can be much more complicated, for example, here another one:

        cells = [
            [
                "Lorem ipsum",
                "Lorem ipsum2",
                [
                    ["111", "222"]
                ]
            ],
            [
                "Lorem ipsum1",
                "Lorem ipsum12"
            ],
            [
                "Lorem ipsum2",
                "Lorem ipsum22"
            ],

Update 1:

Thank to @binariedMe i have solution, here alternative for array above, but with using only chained functions:

        cells
            .tsoAddRow()
                .tsoAddCell("Lorem ipsum")
                .tsoAddCell("Lorem ipsum")
                .tsoAddCell(
                    new Array().tsoAddRow()
                        .tsoAddCell("111")
                        .tsoAddCell("222")
                    )
            .tsoAddRow()
                .tsoAddCell("Lorem ipsum1")
                .tsoAddCell("Lorem ipsum12")
            .tsoAddRow()
                .tsoAddCell("Lorem ipsum2")
                .tsoAddCell("Lorem ipsum22");

Solution

  • make this function for tsoAddCell

    Array.prototype.tsoAddCell = function (value) {
      this.length && this[this.length-1].push(value); return this;
    };
    

    And make tsoAddRow function like this :

    Array.prototype.tsoAddRow = function () {
      this.push([]);
      return this;
    };
    

    Explanation :

    adding cell shall be done on the last row added but to chain everything we need to every time return the original array so that we can perform next task on it. Hence you need to return this from each function.