Determine whether the current time falls within the specified time slots and check if the day is included in the provided array of days

Listing my Weekly Schedule:

weekly_schedule: any[] = [
    {
      id: 0,
      value: 'Monday'
    },
    {
      id: 1,
      value: 'Tuesday'
    }, {
      id: 2,
      value: 'Wednesday'
    }, {
      id: 3,
      value: 'Thursday'
    }, {
      id: 4,
      value: 'Friday'
    }, {
      id: 5,
      value: 'Saturday'
    },
    {
      id: 6,
      value: 'Sunday'
    },
  ]

Business Operational Hours:

business_hours = { day_to: 2, time_to: "23:00", day_from: 5, time_from: "08:00" }

I follow the UTC date format. I am checking if the days in weekly_schedule align with the values given by day_from and day_to.

For instance, if day_from is 5 (Saturday) and day_to is 2 (Wednesday), then the necessary array should be:

["Saturday", "Sunday", "Monday". "Tuesday". "Wednesday"]
. The same logic applies for checking the current time against time_from and time_to.

The code snippet is as follows:

   const activationDate = new Date();

    const d_date = activationDate.getUTCDay() - 1;
    console.log(d_date);

    const B_from = this.getMin(this.business_hours.time_from);

    const B_To = this.getMin(this.business_hours.time_to);


    const min = activationDate.getUTCMinutes();
    console.log(min)
    const naan = activationDate.getUTCHours();
    console.log(naan)
    const utcTime = this.getUtcMin(naan, min);



    for(let j = 0; j < this.business_hours.day_to; j++) {
    for (let i = this.business_hours.day_from; i < this.weekly_schedule.length; i++) {
     
      console.log(this.weekly_schedule[i]);

      if (this.weekly_schedule[i].id === d_date) {
        this.is_open = true;
        console.log(this.weekly_schedule[i].value);
      }
     }
    }

The expected results are not being generated by the current implementation.

Answer №1

It seems that you're interested in treating your array as circular, and then slicing it based on a "from" and "to" index, where both indexes are considered inclusive.

Let's say you have an array of strings like this:

console.log(dayArray);
// ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] 

(which can be easily converted from a structure like:

const dayArray = days_list.reduce<string[]>((a, d) => (a[d.id] = d.value, a), []);

)

Now, you can create a function for circular array slice with inclusive endpoints in various ways. Here is one approach:

function circularArraySlice<T>(arr: T[], fromIndex: number, toIndex: number) {
  return arr.map((_, i, a) => a[(i + fromIndex) % a.length]).
    slice(0, ((arr.length + toIndex - fromIndex) % arr.length) + 1);
}

This function utilizes modular arithmetic to loop back from the end of the array to the beginning using the JS remainder operator (%). Let's test it out:

console.log(circularArraySlice(dayArray, 5, 2));
// ["Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"] 

console.log(circularArraySlice(dayArray, 2, 5));
// ["Wednesday", "Thursday", "Friday", "Saturday"]

This should achieve what you're aiming for. However, do keep an eye out for any potential edge cases.

Click here to access playground code

Answer №2

In order to tackle inquiries such as this one, my suggestion would be to outline a few test scenarios with both anticipated outcomes and the actual results observed.

Upon evaluation, it seems there are a couple of potential issues within the code:

  • The calculation for d_date will yield -1 for Sunday instead of 6 (as expected by days_list)
  • The outer loop (assigning values to j) does not serve any significant purpose since j is not utilized within the loop. Consequently, each iteration will have the same impact.
  • The inner loop (assigning values to i) only seeks days that come after day_from in the days_list array. However, based on your example, days from the beginning of days_list could also match if the value of day_from surpasses day_to.

Answer №3

After studying the insights shared by Randy Casburn in a now-deleted response, it has been uncovered that tackling this issue can be achieved through the utilization of JavaScript's filter method. It is crucial to exercise caution and address distinct scenarios when handling situations where to_date comes before from_date and vice versa.

An illustrative example is as follows:

const days_list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

function getDays(business_hours) {
  const days = days_list.filter((_, id) => {
      if (business_hours.day_from <= business_hours.day_to) {
        return (id >= business_hours.day_from && id <= business_hours.day_to);
      } else {
        return (id <= business_hours.day_to || id >= business_hours.day_from);
      }
  })
  console.log(business_hours, days);
  return days;
}
getDays({ day_from: 2, time_from: "23:00", day_to: 5, time_to: "08:00"});
getDays({ day_to: 2, time_to: "23:00", day_from: 5, time_from: "08:00"});
getDays({ day_from: 3, time_from: "23:00", day_to: 3, time_to: "08:00"});

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 the best way to display JSON responses from AJAX in separate divs with identical class names?

I've been going through a whirlwind of confusion lately, unable to find a solution after spending over 100 hours on this. I'm reaching out for help in hopes that someone can guide me in the right direction! UPDATE: To clarify my issue and seek a ...

Clicking on the Jquery datepicker beforeShowDay remains possible despite all days being set as not selectable

https://i.sstatic.net/P3mII.png I've been using jQuery UI for datepicker and I'm attempting to disable certain dates. I read that this can be done using beforeShowDay when initializing the datepicker, but I'm having trouble getting it to wo ...

What is the best way to create a type that can accept either a string or a

I'm working with a map function and the parameter type is an array of strings or numbers. I've defined it as: (param: (string | number)[]) => ... However, I want to simplify it to: (param: StringOrNumber)[]) => ... Having to repeat the ...

What steps can be taken to modify this jQuery code so that any changes made are also saved to localStorage

I have successfully used jQuery to change the background color of all my divs with the same class (userNumber1) when I check its checkbox. However, I am now looking for a way to save these changes to localStorage, so that they persist each time the page is ...

What is the best way to update the value of a Material Angular select to match its label in TypeScript?

Is there a way to reset the value of this select element back to <mat-label>Select Member</mat-label> in TypeScript when a specific event occurs? I am currently unable to find a solution on the TypeScript side. Any advice would be appreciated ...

Unable to locate Ckeditor toolbar option within Vue (Laravel) framework

Currently, I am utilizing Ckeditor5 for Vue in Laravel. In accordance with the provided documentation, I have gone ahead and installed the necessary modules using the command npm install --save @ckeditor/ckeditor5-vue @ckeditor/ckeditor5-build-classic. Fol ...

Bringing in Bootstrap JavaScript library to a plain HTML project

Currently, I am utilizing Bootstrap version 5.2.3 and attempting to incorporate the JavaScript bundle. <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Big project</title> <link rel ...

When using next.js, a warning may be encountered that states: "A value of NaN was received for the `children` attribute. To resolve this, ensure the value is cast as

I am currently tackling my first Next.js project and have created a file called myCart.js. Below is the code snippet: function orderCard(arr1) { //Code here... } let noRefresh; function makeGetRequest() { //Code here... } export default makeGetReques ...

Having trouble deciphering the code snippet in JavaScript

I'm having trouble grasping the execution of these code lines. What does `project(camera)` do and what is the significance of `screenVector` in this context? function labelBox(Ncardinal, radius, domElement) { this.screenVector = new T ...

Leveraging Interfaces for Dependency Injection in Angular 4

After reading the documentation, I decided to utilize InjectionToken for injecting dependencies through interfaces. I created a simple project with the following code: export interface MyInterface { sayHello(); } @Injectable() export class MyService i ...

Development occurring concurrently within a single Angular project

Just getting started with Angular and gearing up to collaborate on an Angular project with a team of developers. I'm looking for advice on how we can effectively share our work on the Angular development project in real-time, essentially creating a c ...

Choose a property and its corresponding value at random from a JavaScript object

Recently delving into the world of Javascript and seeking guidance. I set out to create a random picker from an array and succeeded with the following setup: var movie = ["star wars", "lotr", "moonlight", "avengers"] function newMovie() { var randomNu ...

What is the best way to delay an observable from triggering the next event?

In my Angular project, I am implementing RxJs with two subjects. s1.next() s1.subscribe(() => { // perform some operation and then trigger the event for s2 s2.next() }); s2.subscribe(() => { // perform some operat ...

When using PWA on an iPhone, the camera feature consistently opens in full screen which makes it difficult to view the HTML button. Adjust

I am currently working on developing a PWA app using the Vue framework that supports camera functionality on both Android and Apple devices. Using mediaDevices, I have successfully enabled the camera and implemented a video stream feature on Android. Addi ...

Transform a string into an object using AngularJS $parse function

Imagine having a server that sends back a response in the form of: { multiply:function(x,y) { return x*y; }, divide:function(x,y) { return x/y; } } Can this be converted into a functional method? I attempted to convert ...

Using JavaScript, verify if a textbox is blank when utilizing the AJAX Control Toolkit's TextBoxWatermark feature

I am currently utilizing the AjaxControlToolkit's TextBoxWatermark feature with an asp.net TextBox to display placeholder text when the box is empty. However, I have encountered an issue where on the client click of a specific button, I need to check ...

Ways to transmit the appropriate model

Using AJAX, I am sending a model to the server via a POST request. I have defined a model and a controller method for processing it. public class TestDto: BaseDto { [Required] public ProductGalleryDto GalleryProduct { get; set; } public int ...

Update various attributes of a div element using JavaScript

I have a progress bar in Bootstrap that receives data through a JavaScript function. Check out the progress bar below: <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" ...

Is there a way to implement JavaScript within my Blazor server razor page to modify the styling of a blazor bootstrap button after a form submission?

I am currently working on a Blazor server application where I am looking to add a special functionality. My goal is to have the accordion header change to red if validation fails, meaning if there is no input in the field. view image here //index.razor pa ...

The bootstrap table did not meet my expectations as I had hoped

I am currently using Bootstrap to create a basic two-column table similar to the one on the Bootstrap website here: http://getbootstrap.com/css/#tables. To achieve this, I have implemented a javascript function to display the table as shown below: $(&bso ...