Coin Combinations
JavaScript
// In order to optimize the process i called
function getRangeDates(dateStart, dateEnd) {
var currentDate = dateStart,
dates = [];
while(currentDate <= dateEnd) {
// add date to array
dates.push(currentDate);
// automatically rolling over to next month
var d = new Date(currentDate.valueOf());
d.setMonth(d.getMonth() + 1);
currentDate = d;
}
return dates;
}
function getWeekdaysOfMonth(date, weekday) {
var month = date.getMonth(),
totalWeekDays = 0;
// Get the first Weekday in the month
while (date.getDay() !== weekday) {
date.setDate(date.getDate() + 1);
}
// Get all the other Mondays in the month,
// after get the first not need to continue one by one
while (date.getMonth() === month) {
totalWeekDays++;
console.log(date);
date.setDate(date.getDate() + 7);
}
return totalWeekDays;
}
/**
* In order
*/
function getTotalMonthsContainingXWeekday(dateStart, dateEnd) {
// Thursday is 4 on javascript weekday, and containing days will be hardcoded
// but could be done dinamically passed as a parameter so can be more dinamic
var weekday = 4, containsWeekdays = 5, totalMonths = 0;
var dates = getRangeDates(dateStart, dateEnd);
// Loop for all the months
for (var i = 0; i < dates.length; i++) {
if (getWeekdaysOfMonth( dates[i], weekday) === containsWeekdays) totalMonths++;
}
return totalMonths;
}
console.log(getTotalMonthsContainingXWeekday(new Date(2015, 6), new Date(2015, 11)))
/**
* Assuming the string is same structure else needed a differentt logic
* "month year month year"
*/
function getTotalMonthsBetweenWith5Thursdays(string) {
var dateStart, dateEnd,
array = string.split(" ");
dateStart = new Date(array[0] + ' ' + array[1] );
dateEnd = new Date(array[0] + ' ' + array[1] );
console.log(dateStart, dateEnd);
}
getTotalMonthsBetweenWith5Thursdays("July 2015 December 2015”);
/* function...