Is there a way to generate a series of time intervals in increments of fifteen minutes using RxJS?

I'm having trouble creating an array of times using RxJS operators in conjunction with Moment.js objects. I initially thought the generate() operator would be a good fit for this task, but it seems to be returning the same time repeatedly instead of incrementing it. Any ideas on what might be going wrong?

After referring to the documentation at

https://rxjs-dev.firebaseapp.com/api/index/function/generate

I learned that I should be able to utilize

generate(startingValue, condition, increment)
to generate an observable that can be piped or subscribed to. However, despite following these instructions, I have not been successful.


times(): void {
        const startTime: Moment = START.clone(); //2019-01-01T16:00:00.000
        const endTime: Moment = END;             //2019-01-01T21:00:00.000
        generate(startTime, time => time <= endTime, time => time.add(15, 'minutes')).pipe(
           toArray()
        ).subscribe(console.log);
}

// returns: [2019-01-01T16:00:00.000, 2019-01-01T16:00:00.000...] 20 times
// desired: [2019-01-01T16:00:00.000, 2019-01-01T16:15:00.000, 2019-01-01T16:30:00.000... ]

Currently, the result is an array containing 20 moment objects, all displaying the same time value.

Answer №1

Although I have yet to utilize the generate() function, it is conceivable that the issue lies in the mutable nature of the moment object. This means that momentObject.add(...) actually modifies the original momentObject. For more information on this behavior, please refer to: https://momentjs.com/guides/#/lib-concepts/mutability/

You may want to attempt the following approach:

generate(startTime, time => time <= endTime, time => time.clone().add(15, 'minutes'))

Answer №2

Why is RxJs necessary to generate an array? Can't we just use Array.from instead? Remember, RxJs is used for creating streams, not arrays.

const createDateRange = (start, end, intervalQuantity, intervalType) => {
  const duration = moment.duration(end.diff(start));
  const interval = moment.duration(intervalQuantity, intervalType);
  return Array.from(
    { length: (duration.asHours() / interval.asHours()) + 1 },
    (_, i) => start.clone().add(moment.duration(intervalQuantity * i, intervalType))
  );
};

console.log(
  createDateRange(
    moment('2019-01-01T16:00:00.000'),
    moment('2019-01-01T21:00:00.000'),
    15,
    'minutes'
  )
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

If you wish to create an observable, you can wrap the array with "of" to emit the entire array at once or use "from" to emit each value individually.

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

Challenges with Loading JSON Dynamically in Next.js using an NPM Package

In my TypeScript project, I have implemented a functionality where a json configuration file is dynamically loaded based on an enum value passed as a parameter to the getInstance function in my PlatformConfigurationFactory file. public static async getIn ...

Angular: handling asynchronous errors when no promise is utilized within a subscription

I am currently working with a material design table and have created custom functions to load the data and extract objects from a JSON array object. Here is a snippet of the code I am using: public getDocumentList() { return this.http.get(this.getDocu ...

I will not be accessing the function inside the .on("click") event handler

Can someone help me troubleshoot why my code is not entering the on click function as expected? What am I missing here? let allDivsOnTheRightPane = rightPane.contents().find(".x-panel-body-noheader > div"); //adjust height of expanded divs after addi ...

What is the best way to extract data from Azure Data Lake and showcase it within an Angular-2 interface?

I am facing a challenge where I need to retrieve files with content from Azure Data Lake and display them in an Angular-2 Component. The issue is that when using the List File Status() method, I am only able to obtain file properties, not the actual conten ...

Is it possible to export all types/interfaces from .d.ts files within multiple folders using index.ts in a React TypeScript project?

In my current React project, I am managing multiple configuration folders: -config -api/ |index.ts |types.d.ts -routes/ |index.ts |types.d.ts ... For example, in the api/index.ts file, I can import necessary types using import {SomeTyp ...

implementing dynamic visibility with ngIf directive in Angular

header.component.html <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a href="#" class="navbar-brand">Recipe Book</a> </div> <div class="collapse na ...

Updating the active tab in the navigation bar whenever the router navigates

I'm struggling with changing the active tab in Angular 2 and Bootstrap 4. I have managed to get the active tab to change using this code snippet: navbar.component.html <nav class="navbar navbar-fixed-top navbar-light bg-faded"> <button cl ...

Tips for transforming a scroll element into the viewport using Angular 2+

This is a sample Here is a component with a list of items: class HomeComponent { text = 'foo'; testObject = {fieldFirst:'foo'}; itemList = [ '1', '2', '3', & ...

Configuring a server-side rendered Angular application on Plesk hosting platform

After successfully setting up server side rendering in my Angular app using nguniversal on my local machine, I am now facing the challenge of implementing this on a remote server with Plesk. In my local environment, I can serve the files by running: npm r ...

Advantages of using index.js within a component directory

It seems to be a common practice to have an index file in the component/container/module folders of react or angular2 projects. Examples of this can be seen in: angular2-webpack-starter react-boilerplate What advantages does this bring? When is it recom ...

Updating Checkbox Appearance in Angular 6 Based on its Checked Status

I have created a checkbox list and I am trying to style the checked item with an underline. Here is my code snippet: TS file: currentQuarter: string; quarters: Observable<MeseRiferimento[]>; q1: MeseRiferimento = new MeseRiferimento(); q2: MeseRife ...

Sometimes the downloaded xlsx file may become corrupted

Currently, I am working on developing a project using Angular4 with Typescript. One of the tasks involved creating a blob utilizing the XLSX-populate library. Below is an example showing the code snippet for generating a valid xlsx object: var url = wind ...

Tips for validating Angular form group input depending on the value of another input within the form?

I am facing an issue with form validation in my Angular version 8 application. I need to validate a form based on the following rules: If a file is uploaded (even if just clicking the button without selecting a file), then the Reason input is not required ...

Issue: The function react.useState is either not defined or its output is not iterable

I'm facing an issue while programming in Next.js 13. Any help or suggestions would be greatly appreciated! Here are the relevant files: typingtext.tsx import React from "react"; export function useTypedText(text: string, speed: number, dela ...

The integration of Meteor Angular2 with Mongodb underwent significant external modifications

I have been experimenting with a basic Meteor Angular 2 application that simply reads from a database. I also have another app that interacts with the same database. However, whenever there is a change in the database, I encounter an error in my Meteor app ...

What is the reason behind having the default router preloaded?

Creating 3 unique pages and a navigation menu. When a menu option is clicked, the page reloads. Template: <a (click)="toLogin()">Login</a> | <a (click)="toHome()">Home</a> | <a (click)="toCatalog()">Catalog</a> ...

What could be causing the failure of the subscribe function to interpret the API response

I want to retrieve user information by using their identification number through a method component.ts identificacion:any = this.route.snapshot.paramMap.get('identificacion'); constructor(private route: ActivatedRoute, private dataService: ...

Utilize dynamic injection of JavaScript code within Angular 5 for enhanced functionality

For nearly a year now, I've been immersed in a project where we started with Angular 2 during its rc versions, and we've since made our way up to version 5. One requirement for our app is the ability to transpile TypeScript code into JavaScript ...

Developing a constrained variable limited to specific values

Recently delving into Typescript - I am interested in creating a variable type that is restricted to specific values. For instance, I have an element where I want to adjust the width based on a "zoom" variable. I would like to define a variable type call ...

Using TypeScript with React Redux, encountering issue of property not being available in the Reducer from the ActionType

Currently, I am learning how to implement a Reducer in Redux while using React with TypeScript. I have encountered an issue that I need help with. Below are the action types that I am working with: import { LoginResponseInterface } from "../../interfaces ...