I'm in trouble trying to reduce this section of code of my function:
checkData(day, month, year, area)
{
if(area == "year" && year == this.year)
return true;
if(area == "month" && month == this.div && year == this.year)
return true;
if(area == "day" && day == this.day && month == this.div && year == this.year)
return true;
return false;
}
How could I simplify/reduce the amount of source code for these IF clauses?
Your if clauses can be rewritten to:
checkData(day, month, year, area)
{
if(year == this.year) {
if(area == "year") return true;
if(month == this.div) {
if(area == "month") return true;
if(day == this.day) {
if(area == "day") return true;
return false;
}
}
}
}
And then to:
checkData(day, month, year, area)
{
if(year != this.year) return false;
if(area == "year") return true;
if(month != this.div) return false;
if(area == "month") return true;
if(day != this.day) return false;
return area == "day";
}
Another possible syntax, depending on the programming language (e.g. C++):
checkData(day, month, year, area)
{
return
year != this.year ? false :
area == "year" ? true :
month != this.div ? false :
area == "month" ? true :
day != this.day ? false :
area == "day";
}
Which could then be written into a single line:
checkData(day, month, year, area)
{
return year != this.year ? false : area == "year" ? true : month != this.div ? false : area == "month" ? true : day != this.day ? false : area == "day";
}
Some languages support such kind of syntax (e.g. C#):
checkData(day, month, year, area) => year != this.year ? false : area == "year" ? true : month != this.div ? false : area == "month" ? true : day != this.day ? false : area == "day";