Michael

Go Back

Clever Code

Posted on 2018-08-30

Most of the time, I wrote "clever" code. At best, a one-liner. Easy to create with some functional JavaScript.

const f = o => o.reduce((a, { b, c }) => [...a, ...(c ? [b * 3] : [])], [])

console.log(
  f([
    { b: '1', c: true },
    { b: '2', c: false },
    { b: '3', c: true },
    { b: '4', c: true },
  ])
)

Today I found this code in my archives. I gave it to a friend and he was like ":-(". He has some basic JS knowledge and said, that he can't understand it.

I re-wrote my code to this:

// array for all option objects
const options = [
  { value: '1', assigned: true },
  { value: '2', assigned: false },
  { value: '3', assigned: true },
  { value: '4', assigned: true },
]

const filter = options
  // only use option objects that have a truthy assigned value
  .filter(option => option.assigned)
  // take the option value and multiply it with 3
  .map(option => option.value * 3)

console.log(filter)

To close this learning, I've found something in my notes: Never ever write "clever" code to increase your ego. Write simple code, so that you and all readers do understand it.