Reputation: 619
I have a string that contains a day of the week (ex "Monday"). I need to figure out how to take this string and get the previous day of the week.
For example if the string contains "Monday" the new string should output "Sunday".
I feel like there is a simple solution (that isn't 7 IF statements) that I'm missing here.
Upvotes: 7
Views: 211
Reputation: 92347
Try
let yesterday = {
'Monday': 'Sunday',
'Tuesday': 'Monday',
'Wednesday': 'Tuesday',
'Thursday': 'Wednesday',
'Friday': 'Thursday',
'Saturday': 'Friday',
'Sunday': 'Saturday',
}
console.log(yesterday['Monday']);
Upvotes: 9
Reputation: 8040
Your solutions could look as follows
const daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const index = daysOfWeek.indexOf('Monday');
console.log(index ? daysOfWeek[index - 1] : daysOfWeek[6]);
You just find a position of the current day and take the previous one in the array. The only check you should make for the index === 0
because negative indexes do not return elements from the end of the array in JavaScript
Upvotes: 2
Reputation: 12209
You don't need a lot of if statements, just a function that uses array.length
and array.indexOf()
:
let daysOfWeek = ["Monday", "Tuesday", "Wednesday","Thursday","Friday","Saturday","Sunday"];
let yesterday = (today) => {
if(daysOfWeek.indexOf(today) === 0){
return daysOfWeek[daysOfWeek.length - 1];
}else{
return daysOfWeek[daysOfWeek.indexOf(today) - 1];
}
}
console.log(yesterday("Sunday"));
Upvotes: 2
Reputation: 829
One straightforward approach, assuming correct input, would be using arrays:
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
previousDay = days[(days.indexOf(currentDay)-1+7)%7];
Upvotes: 6
Reputation: 49945
You can use indexOf
and return Sun
when you exceed array range:
let currentDay = "Mon";
let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
let prevDay = days[days.indexOf(currentDay) - 1 ] || "Sun";
console.log(prevDay);
Upvotes: 3