DEV Community

Discussion on: Introduction to Functional Programming

lukaszahradnik profile image
Lukáš Zahradník

Is that really a valid point? Both indexOf and map in those cases are O(n). Sure, slice doesn't "loop" over an array, but it creates new copy which is again O(n) operation, same for spread.

Your new version looks better, if there wasn't missing indexOf ofc.

Also, question is if it should replace all items with the value or just one.

Thread Thread
lukeshiru profile image
LUKESHIRU • Edited on

You're right, I checked and the performance of my first approach in some scenarios is better, and in some others is the same or even worse. The second one is faster to both map and indexOf+slice. Still my main concern as I expressed previously is using a function meant to map all the elements of an array to just change the value of 1. I didn't checked the actual performance of this and it was kinda surprising, so thanks for pointing that out :D

Thread Thread
lukaszahradnik profile image
Lukáš Zahradník

Agree, I don't find using map for it to be the best and cleanest (kinda misuse of map to be fair). Your second solution is probably the way to go. I don't know if there are better approaches.

Sometimes it's hard to speculate about performance, because spread, spread and indexOf is probably optimized a lot.