Reputation: 817
// 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