andrew.fox
andrew.fox

Reputation: 7933

Use Lodash chain on single value

I want to chain some methods on a single string so that string manipulation looks more readable.

But it seems that chain() works only on collections.

It's not a problem, I just wrap it into array, but to take the final value I have to use zero index operator which looks weird here.

var res = _(["   test   "])
   .map(function(s) { return s + s; })
   .map(_.trim)
   .value()[0];

or TypeScript:

var res = _(["   test   "])
   .map(s => s + s)
   .map(_.trim)
   .value()[0];

How to resolve it?

Upvotes: 2

Views: 1323

Answers (2)

andrew.fox
andrew.fox

Reputation: 7933

The solution was to use head() instead of value():

var res = _(["   test   "])
   .map(function(s) { return s + s; })
   .map(_.trim)
   .head();

or TypeScript:

var res = _(["   test   "])
   .map(s => s + s)
   .map(_.trim)
   .head();

This way res is just a string, and the code is more readable.

Upvotes: 0

Dmitriy  Korobkov
Dmitriy Korobkov

Reputation: 897

There are two functions in lodash:

  1. thru - applies custom function to value in chain;
  2. tap - applies custom function, but not propagates its return value;

Example (pure ES6):

const res = _.chain("   test   ")
       .thru(s => s + s)
       .thru(_.trim)
       .value();

Upvotes: 2

Related Questions