mat.matrixMap()

const matrix_map = {
    /**
     * map a matrix (to become another matrix)
     * @param {function} f with parameters (value, i, j)
     * @example
     * const m = [[1, 2], [4, 5]];
     * m.matrixMap(x => 2 * x)    // [[2,4],[8,10]]
     * m.matrixMap((x, i, j) => i === j ? 1 : 0)  // [[1,0],[0,1]]
     */
    matrixMap(f) {
        return this.map((row, i) => row.map((value, j) => f(value, i, j)))
    }
};

export default matrix_map;

💈範例:

import matrix_map from '../matrix_map.mjs';
Object.assign(Array.prototype, matrix_map);

const m = [[1, 2], [4, 5]]
m.matrixMap(x => 2 * x)                    // [ [ 2, 4 ], [ 8, 10 ] ]
m.matrixMap((x, i, j) => i === j ? 1 : 0)  // [ [ 1, 0 ], [ 0, 1 ] ]

Last updated