Array findLast() and findLastIndex()
indexOf and reduce are the only iteration methods that have "reverse" versions - I think to add any others, a clear case would have to be made that all of them shouldn't get the same treatment.
What's your use case?
An HTML attachment was scrubbed... URL: esdiscuss/attachments/20170804/d4066098/attachment
I'm thinking that this may have performance benefits. The naïve approach would be something like:
function findLast(array, fn) {
return array.reverse().find(fn);
}
Note that this requires a reversed copy of array
to reside in memory before
find
can be run, which is not a particularly useful thing to do when all you
want is to start the search from another direction.
Instead, you would have to do something like:
function findLast(array, predicate) {
for (let i = array.length - 1; i >= 0; --i) {
const x = array[i];
if (predicate(x)) {
return x;
}
}
}
which does the job, I guess. Apart from performance considerations, I would
find it practical if all methods that work in some direction had a
counterpart for the other direction, c.f. trim{Start,End}
, pad{Start,End}
,
reduce{,Right}
. It would be consistent, would it not?
After some research iterators cannot be used because of lack of functions on them. However, for brevity and efficiency these sorts of functions should still exist.
Sebastian
Original Message From: kdex at kdex.de Sent: August 4, 2017 3:10 PM To: es-discuss at mozilla.org Subject: Re: Array findLast() and findLastIndex()
I'm thinking that this may have performance benefits. The naïve approach would be something like:
function findLast(array, fn) {
return array.reverse().find(fn);
}
Note that this requires a reversed copy of array
to reside in memory before
find
can be run, which is not a particularly useful thing to do when all you
want is to start the search from another direction.
Instead, you would have to do something like:
function findLast(array, predicate) {
for (let i = array.length - 1; i >= 0; --i) {
const x = array[i];
if (predicate(x)) {
return x;
}
}
}
which does the job, I guess. Apart from performance considerations, I would
find it practical if all methods that work in some direction had a
counterpart for the other direction, c.f. trim{Start,End}
, pad{Start,End}
,
reduce{,Right}
. It would be consistent, would it not?
An HTML attachment was scrubbed... URL: esdiscuss/attachments/20170804/8c9fbfb3/attachment