const arr1 = [1, 2, 3, 2, 5, 9, 7, 11, 6, 6, 8, 4];
const arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
const arr3 = ['foo', 7.5, 3, {}, 5, 13, 7, 8, 9, 10, 11];
const arr4 = [1,3];
function checkOddSequence(arr, sequenceLength, counter = 0) {
/*
* if the odd numbers counter is equal to the sequence
* length we want, return true
*/
if (counter === sequenceLength) return true;
/*
* if the array has less elements than the sequence
* length we want, return false
*/
if (arr.length < sequenceLength) return false;
if (typeof arr[0] !== 'number' || !Number.isInteger(arr[0]) || arr[0] % 2 === 0) {
/*
* if the first element of the array is not a number
* or is not an integer number or it is an even numbe,
* reset the odd numbers counter
*/
counter = 0;
} else {
// otherwise increment the odd numbers counter
counter++;
}
/*
* re-run the function, passing a copy of the array without the
* first element
* (passing a copy will prevent from modifying the original array)
*/
return checkOddSequence(arr.slice(1), sequenceLength, counter);
}
console.log('arr1:', arr1.join(","),'\nhas arr1 3 consecutive odd numbers?', checkOddSequence(arr1, 3));
console.log('arr2:', arr2.join(","),'\nhas arr2 3 consecutive odd numbers?', checkOddSequence(arr2, 3));
console.log('arr3:', arr3.join(","),'\nhas arr3 3 consecutive odd numbers?', checkOddSequence(arr3, 3));
console.log('arr4:', arr4.join(","),'\nhas arr4 3 consecutive odd numbers?', checkOddSequence(arr4, 3));
console.log('arr1:', arr1.join(","),'\nhas arr1 4 consecutive odd numbers?', checkOddSequence(arr1, 4));
console.log('arr1:', arr1.join(","),'\nhas arr1 5 consecutive odd numbers?', checkOddSequence(arr1, 5));