Last active
April 3, 2024 10:39
-
-
Save well1791/ae62bc4afeb6a46684a6ccd6309dfb96 to your computer and use it in GitHub Desktop.
matrix function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const last = (arr) => arr.slice(-1)[0]; | |
const init = (arr) => arr.slice(0, -1); | |
const matrix = (row, fnRow) => (col, fnItem) => | |
[...Array(row * col).keys()].reduce((z, x) => { | |
const lastRow = last(z); | |
const initRows = init(z); | |
const item = fnItem(x); | |
if (lastRow.length < col) { | |
const rowUpdated = lastRow.concat(item); | |
return rowUpdated.length === col ? | |
initRows.concat([fnRow(rowUpdated)]) : | |
initRows.concat([rowUpdated]); | |
} | |
return initRows.concat([lastRow], [[item]]); | |
}, [[]]); | |
const matrix4r2c = matrix | |
(4, (row) => row.concat(0)) | |
(2, (item) => item + 2) | |
console.log(matrix4r2c); | |
// | |
// [[2, 3, 0], | |
// [4, 5, 0], | |
// [6, 7, 0], | |
// [8, 9, 0]] | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment