コメントありがとうございます。
こっちのほうがシンプルです!
const getZodiacNumber = (month, day) => (
month = `${month}`.padStart(2, '0'),
day = `${day}`.padStart(2, '0'),
new Date(`2000-${month}-${day}`).getDate() === +day && ([
'0321', '0420', '0521', '0622', '0723', '0823',
'0923', '1024', '1123', '1222', '0120', '0219',
].filter(v => v <= `${month}${day}`).length + 9) % 12 + 1) || null;
const zodiacSigns = [
'魚座',
'牡羊座',
'牡牛座',
'双子座',
'蟹座',
'獅子座',
'乙女座',
'天秤座',
'蠍座',
'射手座',
'山羊座',
'水瓶座',
];
// 例: 誕生日が4月15日なら牡羊座(1)
const birthMonth = 4;
const birthDay = 15;
const zodiacNumber = getZodiacNumber(birthMonth, birthDay);
console.log(`星座番号: ${zodiacNumber}`);
console.log(`星座名: ${zodiacSigns[zodiacNumber]}`);
最初のコード
function getZodiacNumber(birthMonth, birthDay) {
const zodiacSigns = [
{ name: '魚座', number: 12, start: [2, 19], end: [3, 20] },
{ name: '牡羊座', number: 1, start: [3, 21], end: [4, 19] },
{ name: '牡牛座', number: 2, start: [4, 20], end: [5, 20] },
{ name: '双子座', number: 3, start: [5, 21], end: [6, 21] },
{ name: '蟹座', number: 4, start: [6, 22], end: [7, 22] },
{ name: '獅子座', number: 5, start: [7, 23], end: [8, 22] },
{ name: '乙女座', number: 6, start: [8, 23], end: [9, 22] },
{ name: '天秤座', number: 7, start: [9, 23], end: [10, 23] },
{ name: '蠍座', number: 8, start: [10, 24], end: [11, 22] },
{ name: '射手座', number: 9, start: [11, 23], end: [12, 21] },
{ name: '山羊座', number: 10, start: [12, 22], end: [1, 19] },
{ name: '水瓶座', number: 11, start: [1, 20], end: [2, 18] }
];
for (const zodiac of zodiacSigns) {
const [startMonth, startDay] = zodiac.start;
const [endMonth, endDay] = zodiac.end;
if (
(birthMonth === startMonth && birthDay >= startDay) ||
(birthMonth === endMonth && birthDay <= endDay) ||
(birthMonth > startMonth && birthMonth < endMonth)
) {
return zodiac.number;
}
}
return null; // 該当しない場合
}
// 例: 誕生日が4月15日なら牡羊座(1)
const birthMonth = 4;
const birthDay = 15;
const zodiacNumber = getZodiacNumber(birthMonth, birthDay);
console.log(`星座番号: ${zodiacNumber}`);