Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function sumUpDiagonals(matrix) {
- try {
- const len = matrix.length;
- matrix.forEach((subArray) => {
- if(subArray.length !== len) {
- throw new SyntaxError('не вкадратная матрица');
- }
- });
- return matrix
- .map((subArray, firstElIndex) => {
- const secondElIndex = subArray.length - 1 - firstElIndex,
- firstEl = subArray[firstElIndex],
- secondEl = subArray[secondElIndex];
- const notNum = (element) => typeof element !== 'number' || isNaN(element);
- if (notNum(firstEl) || notNum(secondEl)) {
- throw new SyntaxError('Input data is not a number.')
- }
- return firstEl === secondEl ? (firstEl * 2) : (firstEl + secondEl);
- })
- .reduce((prevElement, nextElement) => prevElement + nextElement);
- } catch (error) {
- return error;
- }
- }
- let matrixExample = [
- [ 1, 2, 3, 4,],
- [ 4, 5, 6, 5 ],
- [ 7, 8, 9, 7 ],
- [ 7, 8, 9, 7 ]
- ];
- alert(sumUpDiagonals(matrixExample));
Add Comment
Please, Sign In to add comment