リファクタリング
実装した機能に影響を与えずに、ソースコードを読みやすい状態に改善すること
例A
const getYear = (year) => {
if (year % 4 == 0){
if (year % 100 == 0 && year % 400 != 0){
console.log(`${year}年は閏年ではありません`);
} else {
console.log(`${year}年は閏年です`);
}
}else {
console.log(`${year}年は閏年ではありません`);
}
};
例B
const isLeapYear = (year) => {
if (year % 400 == 0) {
// 400で割り切れる年は閏年
return true;
}
if (year % 100 == 0) {
// 400で割り切れず、100で割り切れる年は平年
return false;
}
if (year % 4 == 0) {
// 400でも100でも割り切れず、4で割り切れる年は閏年
return true;
}
// それ以外は平年
return false;
};
if (isLeapYear(year)) {
console.log(`${year}年は閏年です`);
} else {
console.log(`${year}年は閏年ではありません`);
}