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.

Revisions

  1. mihaisavezi created this gist Mar 21, 2022.
    58 changes: 58 additions & 0 deletions draft-vs-final.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    // 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;
    });