Created
May 7, 2019 15:25
-
-
Save jeanbenitez/5944c392538b6955936622386192cf65 to your computer and use it in GitHub Desktop.
Simple array to matrix algorithm with Typescript
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
/** | |
* Convert simple array into two-dimensional array (matrix) | |
* | |
* @param list The array | |
* @param width The num of elements per sub-array | |
* @return the new matrix | |
*/ | |
export const listToMatrix = <T>(list: T[], width: number): T[][] => { | |
const matrix = []; | |
for (let i = 0, k = -1; i < list.length; i++) { | |
if (i % width === 0) { | |
k++; | |
matrix[k] = []; | |
} | |
matrix[k].push(list[i]); | |
} | |
return matrix; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment