DEV Community

Discussion on: Layman's Guide to Higher-Order Functions

Collapse
 
nikoheikkila profile image
Niko Heikkilä

Your point is very valid, and there are two schools here:

One might do this:

someBigArray
    .filter(conditionA)
    .filter(conditionB)
    .filter(conditionC)

Whereas, the other might do this:

someBigArray.filter(conditionA && conditionB && conditionC)

Both are fine, and the worst-case complexity is still O(n). I wouldn't be surprised if some compilers would actually interpret several similar filters as one unified filter.

"The cleaner one isn't the best all the time."

There are no right answers to this. I tend to choose readability over speed unless I know the problem domain is data-heavy and I expect arrays with millions of elements to be the typical input. However, in that case I would probably try to use another data structure than plain arrays to handle such data.

Collapse
 
mrmowji profile image
Mojtaba Javan • Edited

I think you misunderstood what I meant by not separating comparisons. That's my fault I guess.

With these two groups of codes you mentioned in the comment, your comparisons are still separated. That reflects to how deep you decide to abstract your code to get better single-responsibility. One might not stop there and go deeper and separate /A+/.test() from /B+/.test(), etc. and then define an arrow function for each. I mean you need a better example for your argument perhaps so that using higher order functions makes more sense.

Being O(n) is relative. If the number of your comparisons be equal to or greater than your n (the length of password) then we get O(n^2). And you architectured your code so it'd easily accept more comparisons/checks since you want single-responsibility.

IMO you over-engineered your code before the needs arise (the need to add more conditions which can be done easily even without higher-order functions). On the other hand I believe the speed/performance always matters, no matter how fast our computers become.

I'd go with speed, it’s a problem when it’s a problem, and readability, in no specific order, but having them all in mind.

Thread Thread
 
nikoheikkila profile image
Niko Heikkilä

Thanks for your input. Regular expressions were simply an example here to quickly whip out short functions.

In a real application, you could have validations for minimum length, ratio of symbols to alphabets, and even a side-effect introducing function that checks password from Have I Been Pwned database (or other service). As you know, using those as an example would have made the post confusing and I tried to keep this as beginner-friendly as possible.