Created
December 11, 2020 09:04
-
-
Save galElmalah/b40814ea94bd18dfc55a175b8d2dc4e4 to your computer and use it in GitHub Desktop.
This file contains 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
type MatrixFn = ( | |
cell?: any, | |
{ y, x }?: { y: number; x: number }, | |
matrix?: any[][] | |
) => any; | |
export const Matrix = (matrix: any[][]) => { | |
return { | |
forEach(fn: MatrixFn) { | |
matrix.forEach((_, row) => { | |
_.forEach((e, col) => { | |
fn(e, { y: row, x: col }, matrix); | |
}); | |
}); | |
}, | |
map(fn: MatrixFn) { | |
const newMat = []; | |
this.forEach((cell, { x, y }, matrix) => { | |
if (!newMat[y]) { | |
newMat[y] = []; | |
} | |
newMat[y].push(fn(cell, { x, y }, matrix)); | |
}); | |
return newMat; | |
}, | |
print() { | |
matrix.forEach((_, row) => { | |
let c = ''; | |
_.forEach((cell, col) => { | |
c += cell; | |
}); | |
console.log(c); | |
}); | |
}, | |
eq(matrix2: any[][]) { | |
return matrix.every((_, row) => | |
_.every((cell, col) => matrix2[row][col] === cell) | |
); | |
}, | |
reduce( | |
fn: ( | |
acc?: any, | |
cell?: any, | |
{ y, x }?: { y: number; x: number }, | |
matrix?: any[][] | |
) => any, | |
initialValue?: any | |
) { | |
const hasInitialValue = typeof initialValue !== 'undefined'; | |
let acc = hasInitialValue ? initialValue : matrix[0][0]; | |
this.forEach((value, { x, y }) => { | |
if (!hasInitialValue && x === 0 && y === 0) return; | |
acc = fn(acc, value, { x, y }, matrix); | |
}); | |
return acc; | |
}, | |
matrix, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment