Map() vs for() in Javscript for looping reversely

This is actually perfect example, because this portion of the chain: map(render) is so heavy comparing to anything else it makes the following true:

[...tasks].reverse().map(render) ≈ tasks.map(render)
// Think of it like this: 5 + 10 + 10000 ≈ 10000

What about when the “tasks” are more in number ? @snigo

What kind of scale are we talking about? Let’s consider 1,000,000 shall we? I’ve never tried it but I’m pretty sure that no browser will be able to render million elements, it will just hang forever. With cloning and reversing array of million items we’re talking about sub-millisecond range for each task, so 2ms in the very worst scenario. To put it in perspective, you’re comparing tennis ball with the sun here. Adding tennis ball to the sun won’t change pretty much anything :slight_smile:

Of course, as numbers decrease difference will be less and less noticeable. Browser renders 10000 simple div elements in roughly 70ms, cloning + reversing 10000 elements in about 0.01ms. That’s still 7000x difference - tennis ball and smaller size asteroid :slight_smile:

I don’t mean the order of the results, I mean whether it is important that the map operation happens in a specific order.

.slice().reverse().map(...) might give the same result as .map(...).reverse(), but that depends on your function inside, whether it has certain kinds of side-effects.

Or you could just map through it and then with CSS reverse it, like with a flexbox or a grid.

Three options for iterating backwards without a reverse step:

// Apply the transformation function to
// the callback's return value:
array.map((_, i, arr) => arr[arr.length - 1 - i])
// Apply the transformation function to x:
array.reduce((acc, x) => [x, ...acc], [])
array.reduceRight((acc, x) => acc.concat(x), [])
1 Like