Reputation: 347
I came across this bit of code that I cannot understand.
arr.slice(arr.findIndex(func) >= 0 ? arr.findIndex(func): arr.length, arr.length);
I know that the "?" can be thought of as "then" and the ":" as else. I particularly don't understand what this bit arr.length, arr.length
suppose to mean. If you could explain this to me I'd be thankful
here is the code in full context:
function dropElements(arr, func) {
return arr.slice(arr.findIndex(func) >= 0 ? arr.findIndex(func): arr.length, arr.length);
}
// test here
var result = dropElements([1, 2, 3, 4], function(n) {return n >= 3;});
console.log(result)
Upvotes: -1
Views: 69
Reputation: 13511
Try brake it down:
arr.slice(
arr.findIndex(func) >= 0 ? arr.findIndex(func) : arr.length, // First argument for slice method
arr.length // Second slide argument.
);
Now lets try analyse the first argument of the slise:
arr.findIndex(func) >= 0 ? // If the call of arr.findIndex(func) it is greater than 0
arr.findIndex(func) : // Then return the result of this method call
arr.length // Other wise return the length of the arr
So what does this code does is, start the array slicing from the number returned from the first ternary operator to the length of the array.
Upvotes: 0
Reputation: 2521
Think of it like this:
if(arr.findIndex(func) >= 0) {
startI = arr.findIndex(func);
} else {
startI = arr.length;
}
endI = are.length;
return arr.slice(startI, endI);
...does that help? Basically the ?...: is acting like an if else, then the whole argument is followed by a ..., second argument. Very confusing, and I hate it when folks don't use parens to clarify order of ops.
Upvotes: 1
Reputation: 324610
When you need code explaining, it can be a sign that it's badly written. At the very least a line like that needs a comment explaining it.
Instead, consider rewriting:
function dropElements(arr,func) {
var start = arr.findIndex(func);
if( start < 0) {
// no match
return [];
}
else {
return arr.slice(start);
}
}
Note that the second arr.length
is redundant - .slice()
will slice to the end of the array if not otherwise specified.
Upvotes: 2
Reputation: 8079
If we break up this:
arr.slice(arr.findIndex(func) >= 0 ? arr.findIndex(func): arr.length, arr.length);
we,ll get: arr.slice(begin, end)
where
begin = arr.findIndex(func) >= 0 ? arr.findIndex(func): arr.length
and
end = arr.length
So, this is going to slice from begin
to the end of the given array
Upvotes: 0