@cycxllin/cmpt315-a2
Version:
Fulfills CMPT 315 Assignment 2, MacEwan University Winter 2024.
53 lines (45 loc) • 1.6 kB
JavaScript
/*
Return true or false if an array is a factor chain or not.
Parameters: array of numbers
Returns: bool
-1 if error
*/
function isArrayFactorChain(arr){
if (Array.isArray(arr)){
let notNumError = "Error: All elements on array must be type: number";
if (arr.length > 1){
let prev = arr[0];
//check if prev is type number
if (typeof prev != 'number'){
console.error(notNumError);
return -1;
}
// determine if the next number on array is a factor of the previous
for (let i=1; i<arr.length; i++){
let next = arr[i];
//check if next is type number
if (typeof next != 'number'){
console.error(notNumError);
return -1;
}
if (next % prev == 0){
//next is a factor of the previous number so move on
prev = next;
continue;
} else {
// not a factor of prev so stop and return false
return false;
}
}
//reached end of array and all are factors of previous
return true;
} else { //there is nothing to compare to the first value
console.error("Error: Array must have at least 2 elements");
return -1;
}
} else {
console.error("Error: Parameter passed is not an array");
return -1;
}
}
module.exports = isArrayFactorChain;