I thought that I would get fancy and use filter and reduce to to combine checked boxes and options together into one object structure.
The checked items are: [“capitol”, “caves”, “island”]
and the radio option for each is Rules or Odds: [“Rules”, “Odds”, “Rules”]
I want to combine these two together to be one object with the item names as object keys:
{
"capitol": "Rules",
"caves": "Odds",
"island": Rules"
}
I want to filter only for the checked items so that’s a filter, then use reduce.
So, a filter wants a function to be run with it, and we’ll need getRuleType in the reduce function:
function isChecked(expn) {
return document.querySelector("#js-" + expn).checked;
}
function getRuleType(expn) {
var radio = document.querySelector("#js-" + expn + "Rules");
return radio.checked
? "rules"
: "odds";
}
which we can then use with a filter and a reduce function:
return allMinis
.filter(isChecked)
.reduce(function combine(minis, expn) {
return Object.defineProperty(minis, expn, getRuleType(expn));
}, {});
But no, it’s not that easy because defineProperty doesn’t work that way. Instead you must give is all sorts of other attributes instead:
return allMinis
.filter(isChecked)
.reduce(function combine(minis, expn) {
return Object.defineProperty(minis, expn, {
value: getRuleType(expn),
writable: true,
enumerable: true,
configurable: true
});
}, {});
And now all of the code for this section is just looking like it’s far too much for what it’s supposed to achieve.
function getMinis(allMinis) {
function isChecked(expn) {
return document.querySelector("#js-" + expn).checked;
}
function getRuleType(expn) {
var radio = document.querySelector("#js-" + expn + "Rules");
return radio.checked
? "rules"
: "odds";
}
return allMinis
.filter(isChecked)
.reduce(function combine(minis, expn) {
return Object.defineProperty(minis, expn, {
value: getRuleType(expn),
writable: true,
enumerable: true,
configurable: true
});
}, {});
}
Some of this is so that the code is easily maintainable, but why does it all have to be so complex?
The alternative is nested code that looks like this:
function getMinis(allMinis) {
var formEls = document.querySelector("#expansions").elements;
return allMinis.reduce(function (minis, expn) {
if (formEls[expn].checked) {
minis[expn] = formEls[expn + "Choice"].value;
}
return minis;
}, {});
}
I can’t help but look at the so-called badly nested code comparing it with the “better” more structured code above it, and ask is it all worth it?