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' }) }));
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jun 26, 2013 at 17:36
\$\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);
}
Simon Forsberg
59.7k9 gold badges157 silver badges311 bronze badges
answered Jun 26, 2013 at 18:43
\$\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\$ Commented Dec 13, 2015 at 10:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.