Home > database >  Generating a number once a day for all users in JavaScript
Generating a number once a day for all users in JavaScript

Time:06-05

I'm relatively new to JavaScript, and I'm looking to create something like a Wordle clone. Like Wordle, I want to generate a new word each day for all users. I've seen solutions with a random number generator that stores the number in localstorage. However, wouldn't this mean each user who goes on the website would have a different number? Is there a simple way to generate the same number for all users on a site?

CodePudding user response:

You can make your own pseudo random generator, these aren’t actually random but they generate numbers based on a seed (which will be the date)

// Get the day of the month with Date object
const day = new Date().getDate();

// And the month to prevent repeats
const month = new Date().getMonth();

Then you can create your function.

To make it seem even more random, you can get the middle numbers and use those.

function random(){
   // Crazy math stuff
   let num = Math.round((day 4) / month * 39163).toString();

   // To convert it back to a number, use the   operator before parentheses
   // Don’t forget to use % on the max value, I just put 31 as a placeholder
   return  (num[2]   num[3]) % 31;
}

This can be changed to fit your needs ^

This will be the same for every user for the entire day since it is pseudo random and based on a seed

CodePudding user response:

Localstorage is a browser feature, It exists only in the client.

You Will need to persist the data somewhere, a database (MySQL, postgres, etc..) or in a file

The easiest way is in a file, you can search Google "save data to file node.js"

  • Related