Mastodon hachyterm.io

The chain method in Ramda and in Lodash are totall different.

Both Ramda and Lodash are utility libraries for JavaScript that make functional programming easier.

I’m following a Udemy course which occasionally uses Lodash functions. And this time the author chose _.chain to transform an array.

Lodash’s chain example:

Creates a lodash wrapper instance that wraps value with explicit method chain sequences enabled. The result of such sequences must be unwrapped with _#value.

var users = [
  { user: "barney", age: 36 },
  { user: "fred", age: 40 },
  { user: "pebbles", age: 1 }
];

var youngest = _.chain(users)
  .sortBy("age")
  .map(function(o) {
    return o.user + " is " + o.age;
  })
  .head()
  .value();
// => 'pebbles is 1'

Ramda’s chain:
Chain m => (a → m b) → m a → m b

chain maps a function over a list and concatenates the results. chain is also known as flatMap in some libraries.

Dispatches to the chain method of the second argument, if present, according to the FantasyLand chain spec.

If second argument is a function, chain(f, g)(x) is equivalent to f(g(x), x).

Acts as a transducer if a transformer is given in list position.

const duplicate = n => [n, n];
R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3]

R.chain(R.append, R.head)([1, 2, 3]); //=> [1, 2, 3, 1]

So, these two are different.

What I needed to solve my problem was Ramda’s pipe.

const sortByAge = R.sortBy(R.prop("age"));

const youngest = R.pipe(
  sortByAge,
  R.map(({ user, age }) => `${user} is ${age}`),
  R.head
)(users);
// => 'pepples is 1'

How very confusing.

Further Reading