Last active
March 14, 2016 12:44
-
-
Save ivancorrales/c23359642d01af4716ae to your computer and use it in GitHub Desktop.
calculate days and months from a month and a number of days
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var task = (function(){ | |
var _days = [31,28,31,30,31,30,31,31,30,31,30,31]; | |
function addDays(date,days){ | |
date.setDate(date.getDate() + days); | |
return date; | |
} | |
function isLeapYear(year){ | |
return year % 4 === 0 ; | |
} | |
function subtractDaysByMonthAndYear(currentMonth,numberOfDays){ | |
var days = numberOfDays-_days[currentMonth.month]; | |
if(currentMonth.month==1 && isLeapYear(currentMonth.year)) | |
days -=1; | |
return days; | |
} | |
function increaseMonth(currentMonth){ | |
if(currentMonth.month>11){ | |
currentMonth.month=0; | |
currentMonth.year++; | |
} | |
return currentMonth; | |
} | |
return { | |
fromMonth: function fromMonth(currentMonth,numberOfDays,monthsCounter){ | |
monthsCounter = monthsCounter || 0; | |
currentMonth = increaseMonth(currentMonth); | |
var days = subtractDaysByMonthAndYear(currentMonth,numberOfDays); | |
currentMonth.month++; | |
return (_days[currentMonth.month]>=days) ? [++monthsCounter,days] : fromMonth(currentMonth,days,++monthsCounter); | |
}, | |
addDays: function(date,days){ | |
return addDays(date,days); | |
} | |
}; | |
})(); | |
var currentMonth = { | |
month:2, | |
year:2016 | |
}; | |
console.log(task.fromMonth(currentMonth,1100)); | |
currentMonth = { | |
month:2, | |
year:2015 | |
}; | |
console.log(task.fromMonth(currentMonth,1100)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment