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

Understanding the functionality of scope in AngularJS is essential for mastering the framework

Why does this code work? app.controller("ctrl", function($scope){ $scope.From = "Santa"; $scope.To = "Claus"; }); And why doesn't this one work? app.controller("ctrl", function(scope){ scope.From = "Santa"; scope.To = "Claus"; }); ...

The Application Insights Javascript trackException function is giving an error message that states: "Method Failed: 'Unknown'"

I've been testing out AppInsights and implementing the code below: (Encountering a 500 error on fetch) private callMethod(): void { this._callMethodInternal(); } private async _callMethodInternal(): Promise<void> { try { await fetch("h ...

Is it possible for JavaScript/React to observe the movement of elements on the webpage?

I'm searching for a solution to detect if an element moves on the screen. Currently, I have an absolute positioned div (acting as a download overlay) that appears when a document is clicked on my website. However, I want it to disappear whenever the d ...

Struggling to construct a binary tree as my descendants are not arranged in the right sequence

I am currently working on building a binary tree using PHP, MySQL, and a jQuery plugin developed by Frank-Mich. Here is the progress I have made so far... DATABASE STRUCTURE CREATE TABLE IF NOT EXISTS `members` ( `id` int(11) NOT NULL AUTO_INCREMENT, ...

- What are the steps to integrate a different JavaScript plugin into a React project?

Lately, I've come across an issue while trying to incorporate a 3rd party plugin into my practice project in Next.js. Considering that I'm fairly new to React, understanding the 'react way' of doing things has proven to be quite challen ...

Grab a hold of the currently active controller in Angular

Is it possible to access a reference to the current instance of the controller from within its definition? My goal is to use `$compile` to create a modal and have it bound to the same controller that initiated its creation. Below is an example of what I w ...

Choose particular spreadsheets from the office software

My workbook contains sheets that may have the title "PL -Flat" or simply "FLAT" I currently have code specifically for the "PL -Flat" sheets, but I want to use an if statement so I can choose between either sheet since the rest of the code is identical fo ...

Using Javascript to retrieve a variable and dynamically updating the source of an HTML iframe

I have two JavaScript variables, 'long' and 'lat', in the code below. My challenge is to append these values to the end of the iframe URL. I would appreciate assistance on modifying the code below to achieve this. The iframe code bel ...

Issue with JavaScript-generated dropdown menu malfunctioning in WebView on Android devices

During my testing of the app on a Galaxy Tab with Android 2.2, I encountered an issue within the WebView component. The problem arises when I have a local HTML page generated dynamically and it contains a SELECT element like this: <select class='d ...

Reveal the class to the global scope in TypeScript

ClassExample.ts: export class ClassExample{ constructor(){} } index.html: <script src="ClassExample.js"></<script> // compiled to es5 <script> var classExample = new ClassExample(); //ClassExample is not defined < ...

What is the ideal approach for setting up the react-native CLI - local module or global installation

I've been following the initial steps to start with React Native from FB's git page at https://facebook.github.io/react-native/docs/getting-started While using nxp or npm installed CLI during the process, I encountered the following error. [!] ...

JavaScript HTTP Requests

I came across this AJAX example in Stoyan Stefanov's book Object Oriented JavaScript on page 275. The example involves requesting three different files. I have a few questions that I was hoping someone could help me with! What does the line xhr.se ...

Error: The Gravatar service is unable to retrieve the property 'get' from an undefined source

I have a basic app with just one controller. I'm trying to debug the output of the Gravatar.get() function in the console. However, I encounter an error saying: "TypeError: Cannot read property 'get' of undefined". I'm confused because ...

Implementing a redirect following the notification

I'm facing an issue with a function that sends form data to Google Sheets. How can I make the redirect button work after displaying an alert message? I attempted using window.location.href='', but it redirects without submitting the data. & ...

Querying a Database to Toggle a Boolean Value with Jquery, Ajax, and Laravel 5.4

I am facing an issue with a button I created to approve a row in a table. It seems that everything is working fine when clicking the button, but there is no change happening in the MySQL database Boolean column. Here is the code for my button: <td> ...

What is the reason for the viewport in three.js renderer not functioning properly on IE browser?

Try setting the viewport with different coordinates: this.renderer.setViewport(50, -50, this.width, this.height); What could be causing issues with IE browser compatibility? ...

Arranging titles on the top of the page in a column format, resembling an index

Has anyone figured out how to make the title of the content stick at the top, one below the other, as the user scrolls? I've been using Bootstrap's Scrollspy, which works fine, but I need a few additional features. You can check out the codepen l ...

Receiving multiple Firebase notifications on the web when the same application is open in multiple tabs

I have implemented firebase push notifications in Angular 7 using @angular/fire. However, I am facing an issue where I receive the same notification multiple times when my application is open in multiple tabs. receiveMessage() { this.angularFireMess ...

Input of data and salt must be provided

(node:35) UnhandledPromiseRejectionWarning: Error: data and salt arguments required. Can someone please assist me in resolving this error that I am encountering? const validatePassword = (password) => { return password.length > 4; }; app.post("/r ...

Storing a screen value with javascript made simple

I need to incorporate memory functions into my calculator, specifically MS (Memory Store), MR (Memory Restore), and MC (Memory Clear). For Memory Store, the screen value of the calculation needs to be saved, so if it's 90 + 7 = 97, that result should ...