This seems to be working fine. I am pretty sure there is a better way to do it. How can my code be improved performance-wise? The main thing bothering me is the nested for-loop.
function arithGeo (arr) {
var isGeometric = false;
var isArithmetic = false;
var diff = arr[2] - arr[1];
var ratio = arr[2] / arr[1];
for (var i = 0; i < arr.length - 1; i++) {
var j = i + 1;
if (diff !== arr[j] - arr[i]) {
for (var k = 0; k < arr.length - 1; k++) {
var l = k + 1;
if (ratio !== arr[l] / arr[k]) {
break;
} else if (l === arr.length-1) {
isGeometric = true;
break;
}
}
} else if (j === arr.length - 1) {
isArithmetic = true;
}
}
if (isGeometric === true) {
return "geometric";
} else if (isArithmetic === true) {
return "arithmetic";
}
else {
return -1;
}
}
console.log(arithGeo([2,4,6,8]));
console.log(arithGeo([2,6,18,54]));
console.log(arithGeo([2,6,1,54]));