ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลขเป็นอาร์กิวเมนต์แรก และ boolean เป็นอาร์กิวเมนต์ที่สอง
Boolean ระบุปีอธิกสุรทิน (ถ้าเป็น true) ตามข้อมูลนี้ ฟังก์ชันควรคืนวันที่ที่จะตรงกับวันที่ n ของปี
ตัวอย่าง
โค้ดด้านล่างนี้
const day = 60;
const isLeap = true;
const findDate = (day = 1, isLeap = false) => {
if(day > 366){
return undefined;
}
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if(isLeap){
days[1]++;
}
let i = -1, count = 0;
while(count < day){
i++;
count += days[i];
}
const upto = days.slice(0, i).reduce((acc, val) => acc + val);
const month = months[i];
const d = count - upto;
return `${month}, ${d}`;
};
console.log(findDate(day, isLeap));ผลลัพธ์
ผลลัพธ์ในคอนโซลคือ
Feb, 29