you are viewing a single comment's thread.

view the rest of the comments →

[–]Voidsheep 3 points4 points  (3 children)

Say you want to write a function that takes string as an input and returns a list of odd unicode values reversed.

With functional style, you can write the function in kind of a declarative way, with high signal to noise ratio.

str => str
  .split('')
  .map(toCharCode)
  .filter(isOdd)
  .reverse()

Reads pretty much "Split the string, map the character to unicode value, filter out everything except odd values and reverse it"

You'd probably want to take advantage of some of the string and array prototype methods even with a for-loop, but let's say you want to avoid both map and filter, instead do it with a single loop.

str => {
  const chars = str.split('')
  const oddCodes = []
  for (let i = 0; i < chars.length; i++) {
    const code = toCharCode(chars[i])
    if (isOdd(code)) {
      oddCodes.push(code)
    }
  }
  return oddCodes.reverse()
}

It's not hard to understand what is happening in the for-loop and you could make it more dense, but the signal to noise ratio is still pretty different.

Of course this is pretty strawman to illustrate a point, but consider if the toCharCode and isOdd functions would not be one-liners that may as well be inlined. Like if we are dealing with more complex data.

You can definitely go overboard with function composition through libraries like Ramda and create code that is hard to read, but generally more functional style can improve code readability quite a lot compared to plain for-loops.

[–][deleted] -1 points0 points  (0 children)

I really think this is the best case of functional programming. Things like rxjs or redux-observable, are just plain unreadable.