Javascript Function Returning Day of Week X Num of Days Later

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.

4

1 Answer

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));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest