iStudent
iStudent

Reputation: 29

Is there a way to simplify this if condition or do I just accept that this is never gonna be DRY?

This is the code that Im working on

    testCheckNull(value, student) {
    // Check for college applicants
    if (value == "college") {
      if (student.grade != null) {
        return value + " ready"
      } else if (student.sat != null) {
        return value + " not ready"
      }
    }

    // Check for the rest of applicants
    if (student.grade != null) {
      return value + " ready (non-college)"
    } else if (student.sat != null) {
      return value + " not ready (non-college)"
    }
}

So if you notice the nested and last set of if condition are really just repeating itself with the difference to see if the applicant is for college, Im trying to lean out the code and avoid redundancy -- is there a way to simplify this?

Upvotes: 0

Views: 93

Answers (3)

MGX
MGX

Reputation: 3521

Construct along the way

testCheckNull(value, student) {
    let ret = value;

    ret += student.grade ? ' ready' : student.sat ? ' not ready' : '';
    ret += value === 'college' ? '' : ' (non-college)';

    return ret;
}

Upvotes: 0

Alvison Hunter
Alvison Hunter

Reputation: 673

Well, we need to consider the fact that sometimes Object Student might have these values set to null, hence we need to validate that as the default response. The rest is a matter of reducing the code and passing a most proper formatting option for this, take a look at this snippet of code, pal.

const testCheckNull = (value, student) => {
  let collegeMsg = value == "college" ? "ready" : "ready (non-college)";

  if (student.grade != null) {
    return `${value} ${collegeMsg}`;
  } else if (student.sat != null) {
    return `${value} not ${collegeMsg}`;
  }

  return `${student.name} has neither Sat nor Grade acceptable values`;
};

const studentSat = { name: "Alvison Hunter", sat:null, grade:null };
console.log(testCheckNull("college", studentSat));

Upvotes: 0

Amadan
Amadan

Reputation: 198436

Sure — extract the repeating part, and parametrise the difference:

const nonCollegeParenthetical = value == "college" ? "" : " (non-college)";
if (student.grade != null) {
  return value + " ready" + nonCollegeParenthetical;
} else if (student.sat != null) {
  return value + " not ready" + nonCollegeParenthetical;
}

Upvotes: 3

Related Questions