const handleWeek = () => {
function selectWeek(date) {
return Array(7).fill(new Date(date)).map((el, idx) =>
new Date(el.setDate(el.getDate() - el.getDay() + idx)))
}
const date = new Date();
console.log(selectWeek(date));
}
Advertisement
Answer
Since the number of days you’ll get will vary, it doesn’t make sense to create an array with a specific length up front.
I think I’d just use a do-while loop:
const MONDAY = 1; // The Date.prototype.getDay value for Monday
function selectWeek(date) {
const dates = [new Date(+date)];
let dt = new Date(+date);
do {
// Move back a day
dt.setDate(dt.getDate() - 1);
// Remember this day
dates.unshift(new Date(+dt));
// Stop looping when we've just pushed Monday
} while (dt.getDay() !== MONDAY);
return dates;
}
console.log(selectWeek(new Date()));Since you said “last Monday,” that assumes that if you pass in a date that is a Monday, you should get eight days of dates (that day and the entire prior week).