mangei
mangei

Reputation: 817

Conditional chain method with Lodash

// node lodash_conditional_chain_method.js
_ = require('lodash');

var data = [{
    label: 'Alice'
}, {
    label: 'Bob'
}, {
    label: 'Charlie'
},{
    label: 'Dave'
},{
    label: 'Eve'
}];

function getLabelString(entries, maxEntries) {
    var s = 'Labels: ';
    var chain = _.chain(entries);

    // conditional chain method
    if (maxEntries !== undefined) {
        chain = chain.take(maxEntries);
    }

    s += chain
        .map('label')
        .sort()
        .join(', ')
        .value();

    if (maxEntries !== undefined && _.size(entries) > maxEntries) {
        s += ', ...';
    }

    return s;
}

console.log(getLabelString(data));
// Labels: Alice, Bob, Charlie, Dave, Eve

console.log(getLabelString(data, 3));
// Labels: Alice, Bob, Charlie, ...

I use lodash to create a concatinated label String. During chaining, I have a chain method (take) which should only be executed if there is a maxEntries value defined. Currently I do this, with an if-statement.

Is there a way to do this in a more "chainful" way?

ps: maybe there is also a nicer way to append ... at the end?

Upvotes: 1

Views: 918

Answers (1)

zangw
zangw

Reputation: 48406

Try this one with slice

var maxLen = (maxEntries !== undefined)? maxEntries: entries.length;
s += _.chain(data)
      .map('label')
      .slice(0, maxLen)
      .sort()
      .join(', ')
      .value();
if (maxLen < entries.length)
  s += ', ...';

Upvotes: 3

Related Questions