I am not a coder, I am messing around with some JavaScript as part of modding a game, so bear with me. This game supports es5/everything Chromium 28 supported.
I had code which pushed a string to an array from a variable, and when the variable was undefined a fixed string was pushed instead:
slotsArray.push({
landing_policy: ai.landing_policy || 'no_restriction'
});
The setup changed such that where ai.landing_policy was set it would contain multiple values, so it become an array. When it wasn't set only a single entry was required.
The same code does not appear to work where an array is in place:
for (var i = 0; i < count; i++) {
slotsArray.push({
landing_policy: ai.landing_policy[i] || 'no_restriction'
});
}
An error is produced because it's trying to check a value from a variable that hasn't been defined. I expected that to cause it to use the fixed value, but apparently that's not what happens, it just fails.
I've changed my approach to the code seen below in full:
if (Array.isArray(ai.landing_policy)) {
for (var i = 0; i < count; i++) {
slotsArray.push({
landing_policy: ai.landing_policy[i]
});
}
}
else {
slotsArray.push({
landing_policy: ai.landing_policy || 'no_restriction'
});
}
This code works, but what I'm looking to understand is whether this was the best solution? The old method felt elegant, while the new one looks a little clumsy.
count, is itai.landing_policy.length? Even if not, IMO your current code looks fine, its intent is quite clear and I don't think there's any clean way to make it more DRY. Also note that since you're usingArray.isArray, that's an ES6 method (and being able to use ES6 is great)var count = ai.copies || 1;is used to set the size of the loop, though in retrospect I could just set the loop by the size of the array given the two values will always be the same (the 1 is a holdover from the failed approach). I'm surprised the es6 function works (I didn't know it was es6) asnavigator.appVersion.match(/.*Chrome\/([0-9\.]+)/)[1]returned "28.0.1500.68", which my understanding is es5, so there must be more going on under the hood than I understand.mapand ternary operator before realizing your code is much more readable. I'd keep it as it is.