-
Notifications
You must be signed in to change notification settings - Fork 0
/
determinant.js
48 lines (42 loc) · 1.52 KB
/
determinant.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const det = (arr, cb)=>{
const calc=(matrix) => {
if(matrix.length ===2){
return (matrix[0][0]*matrix[1][1]-matrix[0][1]*matrix[1][0]);
}
else if(matrix.length >2){
let determinant = 0;
for(let i=0; i<matrix.length; i++){
let subArray = [];
for(let j=0; j<matrix.length; j++){
if(i!==j){
subArray.push(matrix[j].slice(1,matrix[j].length));
}
}
if(i%2===0){
determinant += matrix[i][0]*calc(subArray);
}
else{
determinant -= matrix[i][0]*calc(subArray);
}
}
return determinant;
}
}
if(!Array.isArray(arr)){
return cb(new TypeError('Input an array'));
}
else if(!arr.every(el=> Array.isArray(el))) {
return cb(new TypeError('Array elements not an array'));
}
else if(!arr.every(el=>el.every(subel=>typeof subel ==='number'))){
return cb(new TypeError('All elements of sub arrays should be numbers'));
}
else if(!arr.every(el=>Array.isArray(el))){
return cb(new TypeError('All elements of array should be arrays'));
}
else if(!arr.every(el=>el.length===arr.length)){
return cb(new TypeError('Please input square matrix'));
}
return cb(null, calc(arr));
}
module.exports = { det };