UNPKG

cpt-waffle-lotide

Version:
68 lines (58 loc) 2.21 kB
const DAYS_IN_MONTH:number[] = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; const validMonth = (month:number):boolean => month >= 1 && month <= 12; const validDay = (month:number, day:number):boolean => { return day >= 1 && day <= DAYS_IN_MONTH[month - 1]; } const calculateDayNumber = (month:number, day:number):number => { let dayOfYear = day; for (let i = 1; i < month; i++) { dayOfYear += DAYS_IN_MONTH[i - 1]; } return dayOfYear; } const isMultiple = (numerator:number, denominator:number):boolean => { return numerator % denominator === 0; } const isLeapYear = (year:number) => { const isMultipleFour:boolean = isMultiple(year, 4); const isMultipleOneHundred:boolean = isMultiple(year, 100); const isMultipleFourHundred:boolean = isMultiple(year, 400); if (!isMultipleFour) { return false; } else if (isMultipleFour && !isMultipleOneHundred) { return true; } else { if (isMultipleOneHundred && !isMultipleFourHundred) { return false; } else { return true; } } } const calculateDayInYear = (date:string) => { const splitDate = date.split('/'); const [year, month, day] = splitDate.map((val:string) => Number(val)); DAYS_IN_MONTH[1] = isLeapYear(year) ? 29 : 28; if (validMonth(month) && validDay(month, day)) { const result = calculateDayNumber(month, day); console.log(date, "is day", result, "of the year", year); return result; } else { console.log("Invalid date"); return -1; } } export default calculateDayInYear; /* Below are some simple tests! They run the function with a predetermined parameter and compare the output to the value we are expecting to get! The console.log will output either 'true' or 'false' based on whether or not the function returns a value that matched our expected value. You'll know your code works correctly when all of these tests return 'true'. */ // console.log("Tests:"); // console.log("---------------"); // console.log(calculateDayInYear("1900/3/2") === 61); // console.log(calculateDayInYear("2000/3/2") === 62); // console.log(calculateDayInYear("2012/2/29") === 60); // console.log(calculateDayInYear("2015/12/31") === 365);