3
votes

What I am trying to write is a simple function that takes in a day (D), X number of days and returns the day X days later.

Days can be represented by ('Mon', 'Tue', 'Wed', 'Thu','Fri','Sat','Sun').

X can be any int 0 and up.

For Example D='Wed', X='2', return 'Fri', D='Sat' and X='5', returns 'Wed'.

How do I do this in JS? Any tips and suggestions appreciated.

1
If you have an array const dayNames = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], the problem gets simpler: you only have to work with numbers from 0 to 6.Ry-♦
okay, but how to do the logic for returning the day x days later?user3064626
If you have the number 1, do you have any ideas on how to get the number 3 numbers after it?Ry-♦
D="Sat" and X="5" should be Thursday shouldn't it?Dacre Denny

1 Answers

4
votes

If I understand your question correctly, then perhaps you could do something like the following:

  1. find the index of input "d" against days of the week
  2. apply "x" to offset the found index
  3. apply modulo operator by total number of days (7) to revolve offset index around valid day range
  4. return resulting day by that computed index

Here's a code snippet - hope that helps!

function getWeekDayFromOffset(d, x) {

  // Array of week days
  const days = ['Mon', 'Tue', 'Wed', 'Thu','Fri','Sat','Sun'];
  
  // Find index of input day "d"
  const dIndex = days.indexOf(d);
  
  // Take add "x" offset to index of "d", and apply modulo % to
  // revolve back through array
  const xIndex = (dIndex + x) % days.length;
  
  // Return the day for offset "xIndex"
  return days[xIndex];
}

console.log('returns Fri:', getWeekDayFromOffset('Wed', 2));
console.log('returns Thu:', getWeekDayFromOffset('Sat', 5));