\$\begingroup\$
\$\endgroup\$
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' }) }));
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jun 26, 2013 at 17:36
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
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);
}
Simon Forsberg
59.7k9 gold badges157 silver badges311 bronze badges
answered Jun 26, 2013 at 18:43
-
\$\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 regularfor
, or maybe callforEach
, or use_.each
since underscore/lodash seems to be there. \$\endgroup\$Flambino– Flambino2015年12月13日 10:49:19 +00:00Commented Dec 13, 2015 at 10:49
default