Is there a way for a beginner to follow to come up with clean code solution?

Well, I think that “just keep practicing” is hogwash when when it comes to algorithms. You need computer science fundamentals. IMHO, whoever wrote that solution also does, because:

  1. As Don Knuth would say, we should write code for legibility first.
  2. Boolean logic is a key part of any intro to comp sci class. Being forced to prove that (NOT X) OR (NOT Y) is the same as NOT(x AND Y) is boring, may make you lose interest, blah, blah, blah… But it keeps you from losing interest when you can’t understand things like this. Use that Boolean identity and see whether the “reworded” version makes immediate sense to you.

Knuth’s point (1) about legibility is part of why functional programming is so powerful. You actually LOSE performance by not implementing things with raw loops, but you GAIN programmer productivity in tasks like writing/refactoring/reading code, and from a business standpoint, CPU cycles are often cheaper than programmer time.

I applaud your desire to “do things both ways.” I make myself do it all the time to stay sharp. This becomes really helpful when the edge-cases near the ends of arrays make reading lower-order functions more annoying than reading a bunch of nested for loops with if/else statements in the mix.

If algorithms are messing you up, you do need more practice. But, blind practice isn’t going to get you there. Designed practice, meant to make you do more than learn syntax, is required. I know that CS50 doesn’t do a lot of javascript (Python, I think), but their syllabus looks meaty in terms of the pain points of neophyte programmers who complain about getting lost at the exact same point in the curriculum as you.

If chaining functions is messing you up, more JS practice may really be all you need, with one caveat. Draw this stuff out on some graph paper. Picture the arrays and visualize what each higher-order function is doing.

1 Like