const firstNonConsecutive = arr => arr.find((number, index) => index > 1 && number !== arr[index -1] + 1)
Is there anyone who could help me break the above function down for me ? I wrote a very long code to solve the task and someone sent me a correction and said my code could be simplified.
The first thing I would do to decompose this would be to add curly braces and break it down in multiple lines:
// This function takes an Array
const firstNonConsecutive = arr => {
// And tries to find an item
return arr.find((number, index) => {
return index > 1 && // Starting from index 2 (the first 2 are ignored)
number !== arr[index - 1] + 1; // Where the value is not (previous value + 1)
});
}
console.log(firstNonConsecutive([128, 6, 2, 8])); // 2 -> ??
console.log(firstNonConsecutive([5, 6, 2, 8])); // 2 -> correct
console.log(firstNonConsecutive([5, 6, 7, 8])); // undefined -> correct
Then, if you don't know that method, you could look up some documentation on Array.prototype.find()
. It takes a callback function which it will execute on every item until that callback returns true
(or any truthy value) at some point. If it does, it will return that value. Otherwise, if no item matches the condition, it will return undefined
.
This should be enough to understand what it does?
The weird thing is that is starts from index 2 (index > 1)
. Using this logic, this means the very first item is never checked. Maybe that condition should be index > 0
:
// This function takes an Array
const firstNonConsecutive = arr => {
// And tries to find an item
return arr.find((number, index) => {
return index > 0 && // Starting from index 1 (the first is ignored)
number !== arr[index - 1] + 1; // Where the value is not (previous value + 1)
});
}
console.log(firstNonConsecutive([128, 6, 2, 8])); // 6 -> correct
console.log(firstNonConsecutive([5, 6, 2, 8])); // 2 -> correct
console.log(firstNonConsecutive([5, 6, 7, 8])); // undefined -> correct
Here is a more deconstructed way to write this:
function firstNonConsecutive(arr) {
// Find an item that passes the condition
return arr.find(passesCondition);
function passesCondition(number, index) {
return index > 0 && number !== arr[index - 1] + 1;
}
}
console.log(firstNonConsecutive([128, 6, 2, 8])); // 6 -> correct
console.log(firstNonConsecutive([5, 6, 2, 8])); // 2 -> correct
console.log(firstNonConsecutive([5, 6, 7, 8])); // undefined -> correct