#ActuallyAutistic web dev. Does front of the front-end. Loves perf and minimalism. Prefers HTML, CSS, Web Standards over JS, UX over DX. Hates div disease.
I also named the function and variables differently, because element is easy to confuse with concepts like DOM elements or React elements, so I often prefer talking about array items instead.
You can optimize the above for a more straightforward readability:
The above code is structured so that if you ever decide to remove the mutation in place (which is often favored these days) and instead of length output the resulting array, you can have an optimization that simply returns the original array if no changes were done. It also makes use of do while loops which seem to be used quite rarely.
We can also use regular for loops in a slightly more unusual way if we remove the requirement for future immutability:
Although you'll probably scare those hipster coders who have put their faith on immutability! :D It is a bit weird how they want to waste so much processing power and effort to creating new arrays on every iteration of a loop just to "be sure" they don't do mutation. Anyway, I know I still would get super mega awesome bonus points for using reduceRight since you really don't see that one being used in the wild.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Here are a couple of solutions that avoid the good old for loop just for the sake of avoiding it:
I also named the function and variables differently, because element is easy to confuse with concepts like DOM elements or React elements, so I often prefer talking about array items instead.
You can optimize the above for a more straightforward readability:
The above code is structured so that if you ever decide to remove the mutation in place (which is often favored these days) and instead of length output the resulting array, you can have an optimization that simply returns the original array if no changes were done. It also makes use of
do while
loops which seem to be used quite rarely.We can also use regular for loops in a slightly more unusual way if we remove the requirement for future immutability:
Then finally the functionalish way to do this:
Although you'll probably scare those hipster coders who have put their faith on immutability! :D It is a bit weird how they want to waste so much processing power and effort to creating new arrays on every iteration of a loop just to "be sure" they don't do mutation. Anyway, I know I still would get super mega awesome bonus points for using
reduceRight
since you really don't see that one being used in the wild.