The function is supposed to mimic indexOf() and have the results of:
indexOf([]) // -1
indexOf([ 6 ], 6) // 0
indexOf([ 5, 3, 1, 2, 4 ], 2) // 3
indexOf([ 20, 10, 0, -10, -20 ], 5) // -1
indexOf([ '7', '8', '9' ], 7) // -1
indexOf([ 7, 7, 7 ], 7) // 0
Am I going nuts, or is this better simplifying at least this one line?
function indexOf (array, value) {
if (array.length > 0) {
if (array.includes(value)) {
for (let i = 0; i < array.length; i++) {
if (array[i] === value) {
return i;
}
}
} else {
return -1;
}
} else {
return -1;
}
}
To:
function indexOf (array, value) {
if (array.length > 0 && array.includes(value)) {
for (let i = 0; i < array.length; i++) {
if (array[i] === value) {
return i;
}
}
} else {
return -1;
}
}
In the latter one, I removed the second if statement and just combined it.