HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Add elements to collection conditionally

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
conditionallycollectionelementsadd

Problem

Is there a smarter way to write this code? I used to add all the elements in the collection constructor, something like this:

new OrderWizardStateCollection([new OrderWizardState(..), new OrderWizardState(..)..])


but now, since I have this one conditional addition, I'm writing it this way:

this.state_collection = new OrderWizardStateCollection();
this.state_collection.add(new OrderWizardState({ state: 'basket', phase: this.phase_collection.findWhere({ phase: 'basket' }) }));
this.state_collection.add(new OrderWizardState({ state: 'account', phase: this.phase_collection.findWhere({ phase: 'account' }) }));
if ( _.has(this.regions, "lp") ) this.state_collection.add(new OrderWizardState({ state: 'loyaltypoints', phase: this.phase_collection.findWhere({ phase: 'account' }) }));
this.state_collection.add(new OrderWizardState({ state: 'delivery', phase: this.phase_collection.findWhere({ phase: 'delivery' }) }));
this.state_collection.add(new OrderWizardState({ state: 'payment', phase: this.phase_collection.findWhere({ phase: 'payment' }) }));
this.state_collection.add(new OrderWizardState({ state: 'placeorder', phase: this.phase_collection.findWhere({ phase: 'placeorder' }) }));

Solution

You could do a loop over the elements that you are always adding:

for (var info in ["basket", "account", "delivery", "payment", "placeorder"] {
    this.state_collection.add (new OrderWizardState ({ state: info, phase: this.phase_collection.findWhere ({ phase: info }) }));
}


And to add the special one, you use your if statement and insert it at a specific index:

if ( _.has (this.regions, "lp")) { 
    var state = new OrderWizardState({ state: 'loyaltypoints', phase: this.phase_collection.findWhere({ phase: 'account' }) })
    this.state_collection.insert (2, state);
}

Code Snippets

for (var info in ["basket", "account", "delivery", "payment", "placeorder"] {
    this.state_collection.add (new OrderWizardState ({ state: info, phase: this.phase_collection.findWhere ({ phase: info }) }));
}
if ( _.has (this.regions, "lp")) { 
    var state = new OrderWizardState({ state: 'loyaltypoints', phase: this.phase_collection.findWhere({ phase: 'account' }) })
    this.state_collection.insert (2, state);
}

Context

StackExchange Code Review Q#27812, answer score: 2

Revisions (0)

No revisions yet.