I'm convinced that you have already figured out how to solve this question from all the comments. So I'll just post my answer to give my personal approach to this problem.
I'm pretty sure that it's very difficult to solve this without using:
1: day to number converter (sunday => 0, monday => 1, and so on...
This is because Date.prototype.getDay
returns a number, not in the
word form)
and
2: date addition function (because there are couple of date addition
that we can't avoid (one for deciding the nearest day of the week, and another for creating new dates for the output array), it's better to just make it a function.)
My approach is (although not fully optimized):
1: First, convert the input day to integer form. This can be done in
few ways, but I simply created an array of dates, and used the
indexOf
method to get the day number. But there is another neat way,
which is flexible to any region you live (application of this SOF link).
2: Then, get the nearest date from the current time with day day
(the while loop in the middle). I think it's very easy to read, but we
can use a one liner here. Which will look something like new_day.setDate(new_day.getDate() + (day_num - first_day.getDay() +
(7 * (new_day.getDay() > day_num))));
. But I personally feel this is a
bit nasty, so I prefer the loop method.
3: Finally, create the array of dates. In my code, I first created the
empty array of k items (without fill()
, the array will be [empty,
empty...]
and will be not iterable), then map them to corresponding
dates from calculation.
There is actually a downfall to my method though. When I'm converting
the date object to the form MM/DD/YYYY
, i'm using the
toLocaleDateString
method. But apparently, using
toLocaleDateString()
is risky (see the comment to this SOF
answer), which I'm not really sure why, but if so that would be a
problem.
Also, the output is 5/25/2020
while your expected output is
05/25/2020
. It depends on your expectation, but it might be a
problem.
function addDays(date, day) {
let new_date = new Date(date.getTime());
new_date.setDate(new_date.getDate() + day);
return new_date;
}
function getDates(k, day) {
const day_num = ['sunday', 'monday', 'tuesday', 'wednesday' ,'thursday' ,'friday', 'saturday'].indexOf(day.toLowerCase()) // converting day name to number
let new_day = new Date();
while (new_day.getDay() !== day_num) {
new_day = addDays(new_day, 1)
}
return Array(k).fill().map((_, index) => addDays(new_day, index * 7).toLocaleDateString() )
}
// today is 05/19/2020
console.log(getDates(1, "monday")) // output: [05/25/2020]
console.log(getDates(2, "monday")) // output: [05/25/2020, 06/01/2020]
console.log(getDates(10, "monday"))
console.log(getDates(20, "monday")) // also for k > 10
Hope that helped, cheers! :)