- Coding Beauty
- Posts
- Newsletter 2024 #6
Newsletter 2024 #6
This simple trick transformed 17 lines of JS code to 1 line
Can you solve this coding puzzle?
Featured content
How did these 17 lines of JavaScript code turn into a one-liner function?
It’s easy, you’ll see!
The 1st thing we notice is we’re selecting items from an array – this should NEVER take 3 lines in JavaScript!
We have the destructuring operator to turn this:
Into this:
What else is obvious? A loop and a gradual accumulation - with push.
The biggest reason we use languages like JavaScript and Python instead of Assembly is how much closer to natural language they are.
Or how much they CAN be!
Because sometimes we write code just for it to work without any care about demonstrating what we’re doing to other humans.
And then this backfires painfully down the line. Especially when one of those humans is your future self.
Parts of speech: back to basics
You know your code is natural when it resembles English as much as possible. Like an interesting, descriptive story.
It means you’ve intelligently made the entities and actions in the story to powerfully express the code flow from start to completion.
Nouns
What entities are we talking about?
Variables
Properties (getters & setters)
Classes & objects.
Modules
Every character has a name, so we describe them with expressive nouns and noun phrases.
Not this:
But this: