What is the best way to determine the operational schedule of online stores that have varying business days?

Struggling to automatically calculate the working days for various online stores that operate on different schedules. The challenge lies in some of these stores being open on weekends. It's important to note that JavaScript starts counting days of the week from 0, where 0 corresponds to Sunday.

example
store A, WORKING_DAYS = Tue - Sun
store B, WORKING_DAYS = Mon - Fri
store C, WORKING_DAYS = Mon - Tue
store D, WORKING_DAYS = Fri - Mon
    //  0 (sunday) - 6 (saturday) so if today is thursday, it would be 4
    // workdays fri - tues, which translates to 5 - 2 but let's say today is saturday 
    and we are looking at positive values
    if( dayStart < currentDay < dayEnd){
        return(
            <Text style={[styles.h4,styles.tag,  {backgroundColor:'#4eae5c'}]}>open</Text>
            )
        }
    if(currentDay) {
        return(
            <Text style={[styles.h4,styles.tag, 
        {backgroundColor:'red'}]}>closed</Text>
            )
        }

Considering that Sunday equates to 0 in JavaScript's date structure, how would you determine the time span between Friday and Monday?

Answer №1

You express your interest in determining the operating hours of an online store on a specific weekday, provided you are aware of its opening and closing days. The challenge arises when the store operates from Friday (5) to Monday (1).

One simple solution is outlined in otw's response:

if(dayStart is less than dayEnd) {
  check whether currentDay >= dayStart and currentDay <= dayEnd
} else {
  check whether currentDay <= dayStart or currentDay >= dayEnd
}

Alternatively, we can view weekdays as a modular arithmetic ring of integers modulo 7. By applying modular arithmetic, we can determine if a number n falls within the interval [a, b], even when a exceeds b:

(n - a) mod 7 <= (b - a) mod 7

To address your specific query, we can establish an isOpen() function like this:

function isOpen(currentDay, dayStart, dayEnd){
  return mod(currentDay - dayStart, 7) <= mod(dayEnd - dayStart, 7); 
}

function mod(a, n){
  return (a % n + n) % n; // ensures positive modulo operation
}

You can then invoke this function within your code as follows:

if(isOpen(currentDay, dayStart, dayEnd)) {
  return (
    <Text style={[styles.h4, styles.tag, {backgroundColor: '#4eae5c'}]}>open</Text>
  );
} else {
  return (
    <Text style={[styles.h4, styles.tag, {backgroundColor: 'red'}]}>closed</Text>
  );
}

Answer №2

Below is the information you requested. The day represents the day you want to check, while open and close refer to the first and last open days of the week.

In this code snippet, I'm utilizing moment.js to convert text-based day names into numerical values. However, you can easily adapt this to work with arrays or other data structures.

This implementation is a modified version of a solution found here: Test if number is inside circular interval

The logic is simple - if the open day is less than or equal to the close day, it's a standard range check. You need to verify if the day falls between the open and close days to determine if it's open on that day.

If the open day is greater than the close day, it indicates a wrap-around range. In this case, you must check if the day is either greater than or equal to the open day OR less than or equal to the close day to ascertain its open status.

function isStoreOpen(day, open, close) {

  const dayNum = moment().day(day).day();
  const openNum = moment().day(open).day();
  const closeNum = moment().day(close).day();

  if(openNum <= closeNum) {
    return (dayNum >= openNum && dayNum <= closeNum);
  } else {
    return (dayNum >= openNum || dayNum <= closeNum);
  }

}

// Example for Store A with WORKING_DAYS = Tue - Sun
console.log("Store A (Tue - Sun) is open on Wednesday: " + isStoreOpen("Wednesday", "Tuesday", "Sunday"));

// Example for Store B with WORKING_DAYS = Mon - Fri
console.log("Store B (Mon - Fri) is open on Wednesday: " + isStoreOpen("Wednesday", "Monday", "Friday"));

// Example for Store C with WORKING_DAYS = Mon - Tue
console.log("Store C (Mon - Tue) is open on Wednesday: " + isStoreOpen("Wednesday", "Monday", "Tuesday"));

// Example for Store D with WORKING_DAYS = Fri - Mon
console.log("Store D (Fri - Mon) is open on Wednesday: " + isStoreOpen("Wednesday", "Friday", "Monday"));
console.log("Store D (Fri - Mon) is open on Saturday: " + isStoreOpen("Saturday", "Friday", "Monday"));
console.log("Store D (Fri - Mon) is open on Friday: " + isStoreOpen("Friday", "Friday", "Monday"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

Here is a scenario more closely related to your specific use case:

function isStoreOpen(currentDay, dayStart, dayEnd) {
  if (dayStart <= dayEnd) {
    if (currentDay >= dayStart && currentDay <= dayEnd) {
      return "open"
    } else {
      return "closed"
    }
  } else {
    if (currentDay >= dayStart || currentDay <= dayEnd) {
      return "open"
    } else {
      return "closed"
    }
  }
}

// Example for Store A with WORKING_DAYS = Tue - Sun
console.log("Store A (Tue - Sun) status on Wednesday: " + isStoreOpen(4, 2, 0));

// Example for Store B with WORKING_DAYS = Mon - Fri
console.log("Store B (Mon - Fri) status on Wednesday: " + isStoreOpen(4, 1, 5));

// Example for Store C with WORKING_DAYS = Mon - Tue
console.log("Store C (Mon - Tue) status open on Wednesday: " + isStoreOpen(4, 1, 2));

// Example for Store D with WORKING_DAYS = Fri - Mon
console.log("Store D (Fri - Mon) status on Wednesday: " + isStoreOpen(4, 5, 1));
console.log("Store D (Fri - Mon) status on Saturday: " + isStoreOpen(6, 5, 1));
console.log("Store D (Fri - Mon) status on Friday: " + isStoreOpen(5, 5, 1));

Your actual implementation could resemble something like this:

if (dayStart <= dayEnd) {
  if (currentDay >= dayStart && currentDay <= dayEnd) {
            return(<Text style={[styles.h4,styles.tag,  {backgroundColor:'#4eae5c'}]}>open</Text>);
  } else {
            return(<Text style={[styles.h4,styles.tag,{backgroundColor:'red'}]}>closed</Text>);
  }
} else {
  if (currentDay >= dayStart || currentDay <= dayEnd) {
            return(<Text style={[styles.h4,styles.tag,  {backgroundColor:'#4eae5c'}]}>open</Text>);
  } else {
            return(<Text style={[styles.h4,styles.tag,{backgroundColor:'red'}]}>closed</Text>);
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is a regex with a touch of greed in its capture

I am considering the following options: ' !This is a string! ' '!This is a string !' '! This is a string !' ' ! This is a string! ' ' ! This is a string ' For each of these scenarios, I aim to find ...

Learn how to run a Linux bash command by clicking a button, where the command is generated from user input

HTML: I am presenting two inputs here <input id="range3" type="range" min="0" max="255" value="0" /> <input id="num3" min="0" max="255&q ...

Improving code quality and consistency in Javascript: Tips for writing better code

Hey, I've been experimenting with some code using ajax and have ended up with a lot of repetitive lines. Is there a way to streamline the code without losing functionality? I keep using the .done method multiple times when I could probably just use it ...

How can JavaScript effectively retrieve the JPEG comment from a JPEG file?

How can one properly retrieve the JPEG comment field (not EXIF, but the COM field) from a JPEG file using JavaScript, particularly when running node on the command line? While there are several libraries available for reading EXIF data in JavaScript, I ha ...

Innovative and interactive animated data display

I've taken inspiration from an example and expanded the code to achieve the following: Dynamic height adjustment Accessibility without JavaScript enabled Is this implementation correct? Can it be expected to function properly on most browsers? You ...

Transform TypeScript class into an object

Is there a way to transfer all values from one typescript class, Class A, to another matching class, Class B? Could there be a method to extract all properties of Class A as an object? ...

Validating forms using TypeScript in a Vue.js application with the Vuetify

Currently, I am attempting to utilize Vue.js in conjunction with TypeScript. My goal is to create a basic form with some validation but I keep encountering errors within Visual Studio Code. The initial errors stem from my validate function: validate(): v ...

What is the best way to showcase information within a node framework?

I am looking to create a family tree using the MVC framework. Furthermore, I need to be able to insert data with relationships. I have object data that I would like to display along with its entities in a node structure. Any assistance on this matter wou ...

"Looking to spice up your website with a dynamic background-image

I've encountered a problem with my CSS code for the header's background image. Despite trying various methods to create a slideshow, nothing seems to be working. Can someone provide guidance? I have four banner images named banner1, banner2, bann ...

Finding the index and value of a specific HTML element with jQuery click event

I'm currently working on creating an Ajax function to delete items from a list using Jquery ajax. Here is the HTML structure: <ul> <li><a class="del"><span style="display:none;">1</span></a></li> <li& ...

Resolving conflicts between Bootstrap and custom CSS transitions: A guide to identifying and fixing conflicting styles

I am currently working on implementing a custom CSS transition in my project that is based on Bootstrap 3. The setup consists of a simple flex container containing an input field and a select field. The functionality involves using jQuery to apply a .hidde ...

What could be causing the directive to not trigger the controller method of mine?

Having trouble with my directive not calling the controller method. Here's the code I'm using: Controller: exports.controller = ['$scope', function($scope) { $scope.addParamter = function () { console.log("here ...

What methods can be used to send JSON data in the body of an express router.get request?

I am currently working on setting up an express endpoint to fetch data from an API and return the JSON response in the body. We are receiving JSON data from a rest API as an array and my goal is to utilize express router.get to present this formatted JSON ...

The property 'get' cannot be accessed because the axios module of vue__WEBPACK_IMPORTED_MODULE_0__ is undefined

Having some trouble with Vue and Axios - encountering the following error message: [Vue warn]: Error in created hook: "TypeError: can't access property "get", vue__WEBPACK_IMPORTED_MODULE_0__.default.axios is undefined" Here's the code snippet: ...

How to Safely Merge Data from Several Excel Files into a Single Worksheet in Google Sheets using ExcelJS without Overwriting Existing Data

Just to clarify - I'm not a seasoned developer, I'm still a newbie at this. My current challenge involves transferring data from multiple Excel files located in one folder to a single worksheet in Google Sheets. To do this, I am utilizing excelJ ...

Navigating through the img src using JavaScript

Currently, I am working on a task that involves the following code snippet: <input type="file" id="uploadImage" name="image" /> <input type="submit" id="ImageName" name="submit" value="Submit"> My goal is to have the path of the selected imag ...

What is the best way to reach the parent controller's scope within a directive's controller?

In a scenario where I have a custom directive nested inside a parent div with a controller that sets a variable value to its scope, like this: html <div ng-controller="mainCtrl"> <p>{{data}}</p> <myDirective oncolour="green" ...

Discovering the most recently selected element in jQuery

Currently reading a jQuery tutorial from the Head First series and practicing with an example where I need to identify the last selected element. In Chapter 2, there is a task involving four images on a page. When a user clicks on any of these images, the ...

The specified container does not exist in the DOM: MERN

I am currently working on a project where I aim to develop a Web Application featuring a stock dashboard. During my coding process, I encountered a minor issue that can be seen in this image. My goal is to have a login form displayed on the browser using ...

The positioning of the Material Ui popover is incorrect

I am currently working on a web application project with React and have implemented Material UI for the navbar. On mobile devices, there is a 'show more' icon on the right side. However, when I click on it, the popover opens on the left side disp ...