iso-weeks-year
Version:
Library to view week numbers for a year
70 lines • 2.66 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.weeksInMonth = void 0;
const daysInMonth_1 = require("./daysInMonth");
const internal_error_1 = require("./error/internal-error");
const firstDayWeek_1 = require("./firstDayWeek");
const getSixDays_1 = require("./getSixDays");
const treat_1 = require("./treat");
const complementLastWeek = (month, year, weeks) => {
let yearWeek = year;
let monthWeek = month;
if (weeks[0].data.length < 7) {
const lastDays = getSixDays_1.getSixDays(month - 1, year);
monthWeek = treat_1.treatMonth(month - 1);
yearWeek = treat_1.treatYear(month - 1, year);
weeks[0].year = weeks[0].data.length === 6 ? weeks[0].year : yearWeek;
weeks[0].month = weeks[0].data.length === 6 ? weeks[0].month : monthWeek;
weeks[0].monthRef = month;
weeks[0].data = [
...lastDays.splice(weeks[0].data.length - 1),
...weeks[0].data,
];
}
const length = weeks[weeks.length - 1].data.length;
const lastPos = weeks.length - 1;
if (length < 7) {
const firstDays = getSixDays_1.getSixDays(month + 1, year, false);
monthWeek = treat_1.treatMonth(month + 1);
yearWeek = treat_1.treatYear(month + 1, year);
weeks[lastPos].year =
weeks[lastPos].data.length >= 2 ? weeks[lastPos].year : yearWeek;
weeks[lastPos].month =
weeks[lastPos].data.length >= 2 ? weeks[lastPos].month : monthWeek;
weeks[lastPos].monthRef = month;
weeks[lastPos].data = [
...weeks[lastPos].data,
...firstDays.splice(0, 7 - length),
];
}
return weeks;
};
exports.weeksInMonth = (month, year, weeks = [], day = 1, weekIndex = 0, loopFinish = false) => {
if (month < 0 || month > 11)
throw new internal_error_1.InternalError('Error: invalid month!');
if (loopFinish)
return complementLastWeek(month, year, weeks);
const _firstDayWeek = firstDayWeek_1.firstDayWeek(month, year);
const week = [];
for (let j = 0; j < 7; j++) {
if (day > daysInMonth_1.daysInMonth(month, year)) {
break;
}
if ((weekIndex === 0 && j >= _firstDayWeek) || weekIndex > 0) {
week.push(day);
day++;
}
}
if (!week.length) {
return complementLastWeek(month, year, weeks);
}
weekIndex++;
weeks.push({
year,
month,
monthRef: month,
data: week,
});
return exports.weeksInMonth(month, year, weeks, day, weekIndex, weekIndex >= 6);
};
//# sourceMappingURL=weeksInMonth.js.map