javascript function returning day of week x num of days later

Viewed 4093

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.

2 Answers

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

# write a code to return week day after adding k number Week_name=("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
#example ('Wed',2) then return Fri 
#example ('Sat',2) then 'Mon'
# here N is postive number from 1 to infinity 
#here S is valid week day name
def week_day(S,K):
    Week_name=("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
    ind=Week_name.index(S)
    #trimming k value from 0 to 6
    K=K%7
    n=len(Week_name)
    print("ind is {0} S is {1} K {2}".format(ind,S,K))
    if ind+K<n:
        return Week_name[ind+K]
    else:
        return Week_name[ind+K-n]
print(week_day('Wed',2))
print(week_day('Sun',2))
print(week_day('Wed',500)) # here 500 converted into 3 as reminder 
print(week_day('Wed',0))
print(week_day('Sat',5))
Related