Skip to content

Instantly share code, notes, and snippets.

@mihaisavezi
Created March 21, 2022 20:09
Show Gist options
  • Save mihaisavezi/856841a3775bf6f7fd9fe33a3f990ca2 to your computer and use it in GitHub Desktop.
Save mihaisavezi/856841a3775bf6f7fd9fe33a3f990ca2 to your computer and use it in GitHub Desktop.
draft-vs-final
// BAD - or what I call draft; comments explain what instead of code being self-explanatory
// Main bit
const formConfig = fieldArray.reduce((fields, field) => {
if (!Array.isArray(fields)) {
field = [field];
}
// Currently last field in section
const last = fields.slice(-1)[0],
lastValue = this.values[last.id];
if (this.values[field.id]) {
// answered fields always show
return [...fields, field];
} else if (this.values[last.id] && lastValue.next_field_id === field.id) {
// this is the next field depending on the previous value
return [...fields, field];
} else {
// this field shouldn't be visible yet
return fields;
}
});
// GOOD - only comment left just explains why, the rest c
const isSectionFirstInArray = (fields) => {
return !Array.isArray(fields);
};
const makeArray = (field) => {
return [field];
};
const getLastValue = (fields) => {
const lastField = fields.slice(-1)[0];
return this.values[lastField.id];
};
const shouldAddToFieldsList = (fields, field) => {
return this.isAnsweredField(fields, field) || this.isNextField(fields, field);
};
// Main bit
const formConfig = fieldArray.reduce((fields, field) => {
if (isSectionFirstInArray(fields)) {
fields = makeArray(fields);
}
if (shouldAddToFieldsList(fields, field)) {
return [...fields, field];
}
// Shouldn't be visible yet - I left this, as it explains what cannot
// reasonably be refactored to be said in words
return fields;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment