array & matrix methods

const array_matrix_methods = {
    
    // ---------------------
    //     array methods
    // ---------------------
    
    // arr.isEmpty
    get isEmpty() { return this.length === 0 },
    
    // arr.last
    get last() { return this[this.length - 1] },
    
    // arr.max(f): f must be a real-valued function
    max(f=x=>x){ return Math.max(...this.map(x => f(x)))},

    // ------------------------
    //     2D array methods
    // ------------------------

    // assuming:
    // - elements in array are themselves arrays.
    // - an element in array is called a "row".

    // arr2d.numberOfRows
    get numberOfRows() { return this.length },
    
    // arr2d.maxRowLength
    get maxRowLength() { return this.max(row => row.length) },

    // arr2d.maxColumnIndex
    get maxColumnIndex() { return this.maxRowLength - 1 },

    // arr2d.transpose
    get transpose() {
        return Array.from({length: this.maxRowLength}, (_, j) => 
            this.map(row => row[j])
        );
    },

    // arr2d.map2D()
    map2D(f) {
        return this.map((row, i) => 
            row.map((value, j) => f(value, i, j))
        )
    },

    // ---------------------
    //     matrix methods
    // ---------------------

    // assuming:
    // - every element (row) is still an array of the same length

    // matrix.numberOfColumns
    get numberOfColumns() { return this[0].length },
};

Last updated