// 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; });