DEV Community

Discussion on: Daily Challenge #252 - Everybody hates Mondays

Collapse
 
peterlau profile image
Peter Lau

JavaScript version without outside packages. It takes me such a long time. Still doubt if it can pass all the tests, while CodeWar ask for a Java version.

const oneWeek = 7 * 24 * 3600 * 1000
const oneDay = 24 * 3600 * 1000
const getWorkDate =  ([year, month, day]) => [year+22, month, day]
const getRetireDate = ([year, month, day]) => [year+78, month, day]
const getDate = ([year, month, day]) => new Date(year, month-1, day)
const formatMonday = number => `${number} Monday${number == 0 || number == 1 ? '' : 's'}`

const cmpDate = (date1, date2) => {
    for (let i=0;i<3;i++) {
        if(date1[i]>date2[i]) return 'large'
        if(date1[i]<date2[i]) return 'less'
    }
    return 'equal'
}



const countMonday = (birthDate, currentDate) => {
    let count = 0
    const workDate =  getWorkDate(birthDate)
    const retireDate = getRetireDate(birthDate)
    if(cmpDate(currentDate, workDate) == 'less') return formatMonday(count)
    const endDate = cmpDate(currentDate, retireDate) != 'less' ? retireDate : currentDate

    const workWeekDay = getDate(workDate).getDay()
    const endWeekDay = getDate(endDate).getDay()
    console.log(workWeekDay, endWeekDay)

    const duration = getDate(endDate).getTime() - getDate(workDate).getTime() + oneDay
    const weekCount = parseInt(duration/oneWeek)
    console.log(duration, oneWeek, duration % oneWeek)
    if (duration % oneWeek != 0 && (
        endWeekDay < workWeekDay || endWeekDay == 1
    )) {
        count = weekCount + 1
    } else {
        count = weekCount
    }
    return formatMonday(count)
}

birth = [1995, 4, 3]
current = [2017, 4, 3]
console.log(countMonday(birth, current))

birth = [1995, 4, 2]
current = [2018, 4, 2]
console.log(countMonday(birth, current))

Enter fullscreen mode Exit fullscreen mode