Here is an auxiliary function that computes the length of the most long subarray of an array.
const maxConsecutive = (arr) => {
const result = arr.reduce((a, b) => {
const { count, maxCount, cons } = a;
if (cons.length === 0)
return { count: 1, maxCount: Math.max(1, maxCount), cons: cons.concat([b]) };
else {
const last = cons.at(-1);
const isCons = (b - last) === 1;
return {
count: isCons ? count + 1 : 0,
maxCount: isCons ? Math.max(count + 1, maxCount) : maxCount,
cons: isCons ? cons.concat([b]) : []
};
}
}, { count: 0, maxCount: 0, cons: [] });
return result.maxCount;
}
Sample outputs:
maxConsecutive([])
> 0
maxConsecutive([0,1,2,3,4])
> 5
maxConsecutive([0,1,2,3,5])
> 4
So now, it's pretty obvious how it can be helpful to check whether the array is consecutive or not: it suffices to maxConsecutive(arr) === arr.length.
[{ value: "4" }]