How to use the chain function from underscore

Find comprehensive JavaScript underscore.chain code examples handpicked from public code repositorys.

underscore.chain creates a chainable object that allows chaining of Underscore methods together.

208
209
210
211
212
213
214
215
216
217
    next();
}

// Actions
mapGamesToGameSummaries(games) {
    return _.chain(games)
        .map((game) => game.getSummary())
        .sortBy('createdAt')
        .sortBy('started')
        .reverse()
fork icon79
star icon121
watch icon8

250
251
252
253
254
255
256
257
258
259
    _.each(this.conflictDiscard, card => {
        this.moveCard(card, 'conflict deck');
    });
    // Move cards to the discard in reverse order
    // (helps with referring to cards by index)
    _.chain(newContents).reverse().each(name => {
        var card = this.findCardByName(name, 'conflict deck');
        this.moveCard(card, 'conflict discard pile');
    });
}
fork icon18
star icon17
watch icon0

+ 3 other calls in file

How does underscore.chain work?

underscore.chain creates a "chainable" object that allows you to call multiple Underscore methods on the same object in a single line by passing the result of one method to the next method as an argument. It works by returning a wrapper object that has Underscore methods as properties, and the value of the wrapped object is passed as the first argument to these methods.

Ai Example

1
2
3
4
5
6
7
8
const numbers = [1, 2, 3, 4, 5];

const result = _.chain(numbers)
  .map((n) => n * 2)
  .filter((n) => n > 5)
  .value();

console.log(result); // [6, 8, 10]

In this example, _.chain is used to wrap the numbers array and allow for a series of operations to be performed using method chaining. _.map is used to double each number in the array, followed by _.filter to only keep those numbers that are greater than 5. The resulting array is then obtained using .value().