Guest User

Untitled

a guest
Jul 17th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. function sumUpDiagonals(matrix) {
  2.  
  3. try {
  4. const len = matrix.length;
  5.  
  6. matrix.forEach((subArray) => {
  7. if(subArray.length !== len) {
  8. throw new SyntaxError('не вкадратная матрица');
  9. }
  10. });
  11.  
  12. return matrix
  13. .map((subArray, firstElIndex) => {
  14. const secondElIndex = subArray.length - 1 - firstElIndex,
  15. firstEl = subArray[firstElIndex],
  16. secondEl = subArray[secondElIndex];
  17.  
  18. const notNum = (element) => typeof element !== 'number' || isNaN(element);
  19.  
  20. if (notNum(firstEl) || notNum(secondEl)) {
  21. throw new SyntaxError('Input data is not a number.')
  22. }
  23. return firstEl === secondEl ? (firstEl * 2) : (firstEl + secondEl);
  24. })
  25. .reduce((prevElement, nextElement) => prevElement + nextElement);
  26.  
  27. } catch (error) {
  28. return error;
  29. }
  30. }
  31.  
  32. let matrixExample = [
  33. [ 1, 2, 3, 4,],
  34. [ 4, 5, 6, 5 ],
  35. [ 7, 8, 9, 7 ],
  36. [ 7, 8, 9, 7 ]
  37. ];
  38.  
  39. alert(sumUpDiagonals(matrixExample));
Add Comment
Please, Sign In to add comment