Creating randomized sample information within a defined timeframe using JavaScript

I'm looking to create mock data following a specific structure.

Criteria:

The time interval for start and end times should be either 30 minutes or 1 hour.

Need to generate 2-3 mock entries for the same day with varying time intervals.

 [{
    Id: 1,
    Subject: 'Bob',
    StartTime: new Date(2020, 6, 11, 9, 30),
    EndTime: new Date(2020, 6, 11, 11, 0),
    CategoryColor: '#1aaa55'
}]

Below is the code snippet I have so far for generating this mock data,

However, I'm unsure about how to implement the data logic. Any assistance would be appreciated.

function random() {
  for (let index = 0; index <= 100; index++) {
    let x = {
      Id: getRandomInt(1, 1000),
      Subject: generateName(),
      StartTime: new Date(2020, 6, 11, 9, 30),
      EndTime: new Date(2020, 6, 11, 11, 0),
      CategoryColor: getRandomColor()
    }
    data.push(x);
  }
}

Answer №1

If you're looking for a tool to generate random names, check out this link. For generating random numbers, you can utilize the Math.random() function (which gives a value between 0-1) in conjunction with Math.floor(). Here's an example:

Math.floor(Math.random() * 101);  // generates a random integer from 0 to 100

To create random dates, refer to this resource.

If you want to specify an interval, follow this format:

let generated_data = []; // stores the final data
let colors = ["Blue", "Red", "Green"]; // define the colors needed


function getRandomInt(min, max) { // generates random number
    return Math.floor(Math.random() * (max - min)) + min;
}

function capFirst(string) { // capitalizes the first letter of a string
    return string.charAt(0).toUpperCase() + string.slice(1);
}


function generateName(){ //outputs random name
    var name1 = ["abandoned","able","absolute","adorable"];
    var name2 = ["people","history","way","art","world"];
    var name = capFirst(name1[getRandomInt(0, name1.length)]) + ' ' + capFirst(name2[getRandomInt(0, name2.length + 1)]);
    return name;
}


function randomDate(date1, date2){ //creates random date
    var date1 = date1 || '01-01-1970'
    var date2 = date2 || new Date().toLocaleDateString()
    date1 = new Date(date1).getTime()
    date2 = new Date(date2).getTime()
    if( date1>date2){
            return new Date(getRandomInt(date2,date1)).toLocaleDateString()   
    } else{
        return new Date(getRandomInt(date1, date2)).toLocaleDateString()  
    }
}

function generateRandomObject() { //appends a random object in the list
    let obj = {
        Id: getRandomInt(1, 1000),
        Subject: generateName(),
        StartTime: randomDate('01/01/2000', '01/01/2020'),
        EndTime: randomDate('01/01/2000', '01/01/2020'),
        CategoryColor: colors[getRandomInt(0, colors.length)]
    }
    generated_data.push(obj);
}


setInterval(generateRandomObject, 30 * 60 * 1000); //executes the function at 30-minute intervals

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 correct method for configuring access permissions?

I'm in the process of developing a user management system, but I keep finding myself having to check the user type for each router. router.get('/admin/settings', (req, res) => { if(admin) { //Proceed. } } router.get(&apo ...

Sending information upwards within an onClick event in a React component

Just starting out with React/ES6 and diving into creating my first components. Currently, I have a PuzzleContainer component that houses a Puzzle component responsible for displaying images. The container component triggers an AJAX call to fetch data on wh ...

Help with enabling the recognition of backspace key in JavaScript?

My current JavaScript is almost perfect but missing one key element. The form has two fields that are disabled when the user fills it out. <label>Can you drive? </label> <input type="booleam" id="drive" disabled><br> <label>W ...

Encountering a problem with Selenium when dealing with tabular data displayed in a DIV format on a website, where each row is encapsulated within its own DIV element

While creating Selenium automation tests for a website with multiple rows contained within a main DIV element, each row represented by a separate DIV. For example, if there are 5 dynamically generated rows, the HTML code structure would look like this: < ...

While attempting to deploy on Vercel, I encountered an error while constructing my Next.js project

While working on my Next login signup project, I encountered the following error: WagmiProviderNotFoundError: `useConfig` must be used within `WagmiProvider`. The documentation for this issue can be found <a href="https://wagmi.sh/react/api/WagmiProvide ...

Manipulating JSON Objects in AngularJS

While I may be proficient in utilizing existing data, my expertise in editing JSON objects is not quite up to par yet. Any assistance in this area would be greatly appreciated. This question may seem basic, but I am seeking clarification as I am unsure. H ...

Programmatically searching individual columns in Datatables is a powerful feature that

I am currently working on creating a jQuery datatable with search functionality in each column, using the example provided on the datatables page found at https://datatables.net/examples/api/multi_filter.html Specifically, I want to be able to search the ...

Storing an array within an AngularJS service for better performance

As someone who is relatively new to AngularJS, I am still in the process of understanding how to utilize services for fetching data in my application. My aim here is to find a method to store the output of a $http.get() call that returns a JSON array. In ...

Engaging three-dimensional design inspired by JavaScript frameworks

I'm interested in developing an interactive 3D application using JavaScript. I'm curious to know if either babylon.js or three.js have support for interactivity. I've searched for information on this but haven't found much, and the docu ...

Creating interactive forms - Incorporating dynamic checkbox options within the expansion panel element

Recently, I developed a basic movie list app with a checkbox list for genre filtering. Initially, I managed to achieve the desired functionality without using reactive forms. However, I am now exploring implementing the same functionality using reactive ...

Javascript Mouse Events Not Functioning Properly with Three.JS Scene Components

Currently feeling quite perplexed (probably due to fatigue from working on this at an inopportune time). I'm in the midst of trying to configure my three.js application to trigger distinct functions based on different mouse events when the cursor hove ...

How to deselect a checkbox in next.js when another one is selected

I'm looking to create a navigation system where clicking on a button scrolls to a specific section. However, I'm wondering how to deselect three inputs when one is selected in next.js using the code below. Do I need to modify each menu item indiv ...

Avoiding an endless JavaScript loop in Selenium/PhantomJS to improve test automation sanity

Imagine a scenario where a web application contains JavaScript code like the one below: for(i=0; i > -1; i++){var a=1}; // Infinite loop If I attempt to navigate this web app using Selenium or PhantomJS, it will become unresponsive indefinitely. Is t ...

Retrieve an array from a JSON data source

When working with the JSON data shown below, my goal is to access the content in the chats field. {"count":41,"count_id":5,"pic":null,"chats":[{"id":13,"user_id":1,"yiinput_id":5,"chat":"i like to say hello"},{"id":14,"user_id":1,"yiinput_id":5,"chat" ...

What could explain why the event listener functions properly on the initial call but fails on subsequent calls?

Currently, I am working on a bootstrap carousel where the "Previous" button is hidden on the first slide and the "Next" button is hidden on the last slide. Now, I want to disable the next button on the second slide (and eventually all slides with iframe vi ...

I'm experiencing difficulties loading data using AJAX

I'm facing an issue with an old script that used to load IP from an xml file. Everything was running smoothly until about six months ago when I tried to use it again and encountered some problems. I'm not sure what went wrong. Could there have be ...

Tips for setting limitations on a date picker's minimum and maximum values on an iPhone using JavaScript

I have encountered an issue with my JavaScript function that sets min and max values for the input type date. While it works perfectly on Android devices, I am facing a problem on iPhone where I am unable to restrict the calendar with the specified min and ...

The Logic Behind Solving Project Euler Problem #11

I recently started challenging myself with Project Euler, but I've hit a bit of a snag on problem 11. The problem requires finding the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) within a 2 ...

Import statements cannot be used outside of a module when working with a private npm package in cucumber.js

Utilizing cucumberjs to test various components of my project has been successful. However, I encountered an issue in one step where I utilize a zod schema that is defined within a private npm module: // within the private npm package: // constant.js impor ...

There was a problem retrieving the product information from the API

I have been struggling to pinpoint the exact issue at hand. The foundation of HTML and CSS is pre-written, with JavaScript responsible for generating the core elements to populate the DOM. Within my script, I am attempting to retrieve product data in ord ...