DEV Community

Discussion on: Example: Imperative vs. Functional

 
gypsydave5 profile image
David Wickes • Edited

Classy! But It still involves a non-referentially transparent function.

const friendFilter = (friend) => friend.drinks.includes(itemToSearch)

itemToSearch is still closed over by the lambda (i.e. it's not one of its arguments).

Before I get into this - I really wouldn't do this in real life! It's fine that the lambda closes over itemToSearch. I'm only doing this because it's fun and I enjoy FP :D.

But since you asked... one way of handling this - if you really, really only wanted pure functions everywhere - would be to pass itemToSearch as an argument and return the friendFilter function, essentially currying the function:

function fun(friends, itemToSearch) {
  const friendFilter = (item) => (friend) => friend.drinks.includes(item)
  const filterItem = friendFilter(itemToSearch)

  return friends
    .filter(friend => filterItem(friend))
    .map(friend => friend.name);
}

Lambda and currying make a great way to add data into your functions as and when its needed.

small refactor:

function fun(friends, itemToSearch) {
  const friendFilter = (item) => (friend) => friend.drinks.includes(item)
  const predicate = friendFilter(itemToSearch)

  return friends
    .filter(predicate)
    .map(friend => friend.name);
}

stupid why-oh-why refactor:

const fun = (friends, itemToSearch) => friends
    .filter((item => friend => friend.drinks.includes(item))(itemToSearch))
    .map(friend => friend.name);

Ridiculous, please-make-it-stop refactor

const fun = (friends, itemToSearch) => 
  (predicate => friends.filter(predicate).map(friend => friend.name))
  ((item => friend => friend.drinks.includes(item))(itemToSearch))

If you enjoy this madness, might I recommend reading some books about the Scheme programming language.

Thread Thread
 
nicholasnbg profile image
Nick Gray

Haha nice, I actually work with Scala day to day and a lot of code ends up looking similar to the second last example (with types).

Thanks again mate :)

Thread Thread
 
miku86 profile image
miku86 • Edited

Thanks for sharing all your insights (all of you), I will have a closer look at them.