3
\$\begingroup\$

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' }) }));
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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);
}
\$\endgroup\$
1
  • \$\begingroup\$ Don't use for..in on arrays in javascript; it enumerates properties - not just the array's elements (also, that line is missing a )). Use a regular for, or maybe call forEach, or use _.each since underscore/lodash seems to be there. \$\endgroup\$
    – Flambino
    Dec 13, 2015 at 10:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.