this post was submitted on 05 Sep 2024
55 points (93.7% liked)
Programming
17373 readers
164 users here now
Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!
Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.
Hope you enjoy the instance!
Rules
Rules
- Follow the programming.dev instance rules
- Keep content related to programming in some way
- If you're posting long videos try to add in some form of tldr for those who don't want to watch videos
Wormhole
Follow the wormhole through a path of communities [email protected]
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
This doesn't seem overly useful.
It's a list taken out of a bunch of books with no regard for how something can be the best path in one language and a smell in another language.
Look at this page for example: https://luzkan.github.io/smells/imperative-loops
It suggests using functional loop methods (
.map()
,.reduce()
,.filter()
) instead of using imperative loops (for
,for in
,for each
) but completely disregards the facts that imperative loops also have access to thebreak
,continue
, andreturn
keywords to improve performance.For example: If I have an unsorted list of 1000 cars which includes a whole bunch of information per car (e.g. color, year manufactured, etc...), and I want to know if there were any cars were manufactured before the year 1980, I can run an imperative loop through the list and early return true if I find one, and only returning false if I haven't found one by the end of the list.
If the third car was made in 1977, then I have only iterated through 3 cars to find my answer.
But if I were to try this with only functional loops, I would have to iterate through all 1000 cars before I had my answer.
A website with blind rules like this is going to lead to worse code.
..what? At least with Java Streams or Kotlin Sequences, they absolutely abort early with something like
.filter().first()
.Same in Python, Rust, Haskell and probably many others.
But apparently JS does work that way, that is its
filter
always iterates over everything and returns a new array and not some iterator object.The old methods on Array will eagerly evaluate all elements. But JS has a new Iterator type with methods that works lazily instead.