Since the reduce with spread technique is exponential in nature, it gets gruesome with just a little increase in data. Wait, isn't this premature optimization?Īs much as I want to say it is, it's probably not. Jake wrote a really nice article about this pattern explaining why you shouldn't use functions as callbacks unless they're designed for it. So let's assume we have a spread operator like this - const obj1 = ) The speed of the spread operator can vary depending upon how your JavaScript is getting compiled, but for the sake of this article, let's consider it is compiled using the v8 engine, which Node and Chrome use.
The latter is still O(n) (yes 3 times O(n) is still O(n), measuring 'hot paths' in code for time complexity is worthless) which is far better that O(n 2) because of the exponential nature of the latter. After all, the spread operator takes almost O(n) time, resulting in the overall time complexity of O(n 2) for the first method. If you see the replies, you'll find how most people are concerned over the fact that the 2nd method is worse (which also doesn't work as expected, as we'll discuss later in this post) because we are iterating the array thrice when in fact the former one is much slower.
#typescript #javascript /3TW57kaCar- Rupert Foggo McKay May 22, 2021
Which is more readable? Notice that when map arranges data exactly how we want, our. reduce calls by doing as much work as possible in.