Generate random string every 24 hours then refresh JavaScript? - javascript

What I have been trying to make may be a bit more complicated than I thought.
So what I am trying to accomplish is... generating a random string of characters through javascript (which I have the code for) but only generating a new one at 12am or every 24hrs.
The code I have should work (doesn't) and that's what I need help with.
<div id="password1">
</div>
<script>
var d = new Date();
var n = d.getDay();
var passwords = [makeid(10)[n]]; //want it to be 10... stay the same characters for 24hrs then change
document.getElementById("password1").innerHTML = passwords[n];
function makeid(length) {
var result = [];
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result.push(characters.charAt(Math.floor(Math.random() *
charactersLength)));
}
return result.join('');
}
</script>
Is it possible with javascript or not, is it a simple solution or syntax error? I have no idea...
I looked in to this and couldn't find any similar posts...

Since you have coded your own password generator, I used your code to make a new password string lasting for 24 hours unless the localStorage gets cleard.
Cookie can be used too but localStorage and Cookie both are not properly runnable through sandbox environments, so try this on your own development environment. Please note that storing private values like passwords is not good for the security.
<div id="password1">
</div>
<script>
function makeid(length) {
var result = [];
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result.push(characters.charAt(Math.floor(Math.random() *
charactersLength)));
}
return result.join('');
}
const key = "keyForTheVulnurablePassword";
if(localStorage.getItem(key) == null) {
let expireDate = new Date();
expireDate.setDate(expireDate.getDate() + 1);
localStorage.setItem(key, JSON.stringify({pw:makeid(10), expire:expireDate}));
}
else {
let currentDate = new Date();
let storedExpireDate = new Date(JSON.parse(localStorage.getItem(key)).expire);
if(storedExpireDate <= currentDate) {
while(storedExpireDate <= currentDate) {
storedExpireDate.setDate(storedExpireDate.getDate() + 1);
}
localStorage.setItem(key, JSON.stringify({pw:makeid(10), expire:storedExpireDate}));
}
}
document.getElementById("password1").innerHTML = JSON.parse(localStorage.getItem(key)).pw;
</script>

<div id="password1">
</div>
<script>
function execute(){
var d = new Date();
var n = d.getDay();
var passwords = [makeid(10)[n]]; //want it to be 10... stay the same characters for 24hrs then change
document.getElementById("password1").innerHTML = passwords[n];
}
function makeid(length) {
var result = [];
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result.push(characters.charAt(Math.floor(Math.random() *
charactersLength)));
}
return result.join('');
}
const milisecondsUntil12Pm = 1000 // Write here the number of Miliseconds until 12 pm at the timeof run this script
setTimeout(()=> {
execute()
setInterval(()=> {
execute()
}, 86400000) // 24 hours * 60 minutes * 60 seconds * 1000 miliseconds = 86400000 Miliseconds
}, milisecondsUntil12Pm)
</script>

Related

Append a parameter to an array and evaluate each array element

I have a script wherein I am pushing each parameter value(Date) to an array and evaluating each element.
if(frame.name == 'bookingConfirmedMbox')
{
var checkinEligible= "false";
var currDate = Date.parse(new Date());
var depDate = frame.param(itineraryParamDate);
var departureDate = depDate.toString();
var travelDateArr = new Array();
travelDateArr.push(depDate);
console.log(travelDateArr);
var travelDateArrlen = travelDateArr.length;
for (var i=0 ; i< travelDateArrlen ; i++)
{
var travelDate = travelDateArr[i].toString();
var depaDate = travelDate.replace(/(\d{2})(\d{2})(\d{4})/, "$2/$1/$3");
var dDate= Date.parse(new Date(depaDate));
var timeDiff = parseInt(dDate - currDate);
var daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
}
if (daysDiff >= 2 && daysDiff <=7 )
{
checkinEligible="true";
}
else
{
checkinEligible="false";
}
return checkinEligible;
}
here, itineraryParamDate is the parameter name of the frame and through frame.param('itineraryParamDate') value is getting stored and appended in an array.
This script is evaluating to false if I set itineraryParamDate as 30112018 //ddmmyyyy.It should evaluate to true.
My doubt is --> var travelDate = i.toString(); is not evaluating to correct value.
Can someone advise me on this ?
function Test() {
//
var frame = new Object;
frame.name = 'bookingConfirmedMbox';
var checkinEligible = false;
var currDate = null;
var strDepDate = "";
var travelDateArr = [];
var travelDateArrlen = 0;
var travelDate = "";
var dDate = "";
var timeDiff = 0;
var daysDiff = 0;
if (frame.name == 'bookingConfirmedMbox') {
currDate = Date.parse(new Date());
strDepDate = "30112018";
travelDateArr.push(strDepDate);
travelDateArrlen = travelDateArr.length;
for (let i = 0; i < travelDateArrlen; i++) {
travelDate = strDepDate.toString();
strDepDate = travelDate.replace(/(\d{2})(\d{2})(\d{4})/, "$2/$1/$3");
dDate = Date.parse(new Date(strDepDate));
timeDiff = parseInt(dDate - currDate);
daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
}
if (daysDiff >= 2 || daysDiff <= 7) {
checkinEligible = true;
} else {
checkinEligible = false;
}
}
return checkinEligible;
} // end Test();
var retval = Test();
var res = (retval) ? "Test worked" : "Test failed";
console.log(res);
The OP has a number of issues with the code sample. If one wishes to get a true or false result, then one ought to use boolean values of true and false because "true" and "false" are non-empty strings and so each evaluates as true. If one wishes to return a value, then one must use a function which in this case is called Test(). Also, the inner if conditional needs to use a logical OR instead of a logical AND. When daysDiff holds a value of 34, as happened on Oct. 26th with this code, then the if conditional only makes sense when using a logical OR. Lastly, no need to redeclare variables in the for-loop. Better to define the values outside the loop and set with default values. In the for-loop you may reassign values to those variables.

How can I parse timespan string to hour, minutes?

I have a string "P18DT5H2M3S" which means: 18 days, 5 hours, 2 minutes, 3 seconds.
I have to parse this string to hour and minute. Should I use regex or split or substr etc...?
(regarding to this How can I convert come string timespan variable from Wcf to hours and minutes?)
You can use whatever you want.
Following is the example using split method with regex.
var res = "P18DT5H2M3S";
var tokens = res.split(/[A-Z]+/);
//var str = "D:"+token[1]+" H:"+tokens[2]+" M:"+tokens[3]+" S:"+tokens[4];
alert("D:"+tokens[1]+" H:"+tokens[2]+" M:"+tokens[3]+" S:"+tokens[4]);
You can do with substr but for this you have to find index of letters. So Spit with regex is simpler approach.
So I took #chandil03's answer and tweaked it to return a HH:MM:SS format.
var stamp = "PT2H10M13S"
// strip away the PT
stamp = stamp.split("PT")[1];
// split at every character
var tokens = stamp.split(/[A-Z]+/);
// If there are any parts of the time missing fill in with an empty string.
// e.g "13S" we want ["", "", "13", ""]
for(var i = 0; i < 4 - stamp.length; i++){
tokens.unshift("");
}
// Here we add logic to pad the values that need a 0 prepended.
var stampFinal = tokens.map(function(t){
if(t.length < 2){
if(!isNaN(Number(t))){
return ("0" + Number(t).toString());
}
}
return t;
});
// pop the last element because it is an extra.
stampFinal.pop();
console.log(stampFinal.join(":"));
I found this page:
http://www.petershev.com/blog/net-timespans-returned-by-breeze-js-or-working-with-iso8601-duration-standard/
So when I added to https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js this js,
I can convert
duration = moment.duration.fromIsoduration('P18DT5H2M3S');
duration._data can be used
it has _days, _hours, _minutes
Please, find my solution based on inoabrian's.
function fromString(timeSpan) {
var hours = 0;
var minutes = 0;
var seconds = 0;
if (timeSpan != null && typeof (timeSpan) == 'string' && timeSpan.indexOf('PT') > -1) {
timeSpan = timeSpan.split("PT")[1].toLowerCase();
var hourIndex = timeSpan.indexOf('h');
if (hourIndex > -1)
{
hours = parseInt(timeSpan.slice(0, hourIndex));
timeSpan = timeSpan.substring(hourIndex + 1);
}
var minuteIndex = timeSpan.indexOf('m');
if (minuteIndex > -1)
{
minutes = parseInt(timeSpan.slice(0, minuteIndex));
timeSpan = timeSpan.substring(minuteIndex + 1);
}
var secondIndex = timeSpan.indexOf('s');
if (secondIndex > -1)
seconds = parseInt(timeSpan.slice(0, secondIndex));
}
return [hours, minutes, seconds];
}

Javascript: reducing down to one number

So I need to take a date and convert it into one single number by adding up each digit, and when the sum exceeds 10, I need to add up the two digits. For the code below, I have 12/5/2000, which is 12+5+2000 = 2017. So 2+0+1+7 = 10 & 1+0 = 1. I get it down to one number and it works in Firebug (output of 1). However, it is not working in a coding test environment I am trying to use, so I suspect something is wrong. I know the code below is sloppy, so any ideas or help reformatting the code would be helpful! (Note: I am thinking it has to be a function embedded in a function, but haven't been able to get it to work yet.)
var array = [];
var total = 0;
function solution(date) {
var arrayDate = new Date(date);
var d = arrayDate.getDate();
var m = arrayDate.getMonth();
var y = arrayDate.getFullYear();
array.push(d,m+1,y);
for(var i = array.length - 1; i >= 0; i--) {
total += array[i];
};
if(total%9 == 0) {
return 9;
} else
return total%9;
};
solution("2000, December 5");
You can just use a recursive function call
function numReduce(numArr){
//Just outputting to div for demostration
document.getElementById("log").insertAdjacentHTML("beforeend","Reducing: "+numArr.join(","));
//Using the array's reduce method to add up each number
var total = numArr.reduce(function(a,b){return (+a)+(+b);});
//Just outputting to div for demostration
document.getElementById("log").insertAdjacentHTML("beforeend",": Total: "+total+"<br>");
if(total >= 10){
//Recursive call to numReduce if needed,
//convert the number to a string and then split so
//we will have an array of numbers
return numReduce((""+total).split(""));
}
return total;
}
function reduceDate(dateStr){
var arrayDate = new Date(dateStr);
var d = arrayDate.getDate();
var m = arrayDate.getMonth();
var y = arrayDate.getFullYear();
return numReduce([d,m+1,y]);
}
alert( reduceDate("2000, December 5") );
<div id="log"></div>
If this is your final code your function is not outputting anything. Try this:
var array = [];
var total = 0;
function solution(date) {
var arrayDate = new Date(date);
var d = arrayDate.getDate();
var m = arrayDate.getMonth();
var y = arrayDate.getFullYear();
array.push(d,m+1,y);
for(var i = array.length - 1; i >= 0; i--) {
total += array[i];
};
if(total%9 == 0) {
return 9;
} else
return total%9;
};
alert(solution("2000, December 5"));
It will alert the result in a dialog.

how to calculate values of an (javascript) object with date keys

I have the following simplified (javascript) object, of which properties are dates (in string fomat):
Given a random startdate and enddate within the range of dates in the object, how to code (efficiently) the calculation - say accumulate- of the values within this range? As an example, for the following code the calculation result should be 12 (3+4+5) for the given startdate and enddate.
var startdate = '2014-01-03';
var enddate = '2014-01-05'
var obj = {};
obj['2014-01-02'] = '2';
obj['2014-01-03'] = '3';
obj['2014-01-04'] = '4';
obj['2014-01-05'] = '5';
obj['2014-01-06'] = '6';
You can just loop through the properties of the object, doing a comparison, and adding.
var startdate = '2014-01-04';
var enddate = '2014-01-05';
var arr = {};
arr['2014-01-02'] = '2';
arr['2014-01-03'] = '3';
arr['2014-01-04'] = '4';
arr['2014-01-05'] = '5';
arr['2014-01-06'] = '6';
var total = 0;
for(var p in arr) {
if(arr.hasOwnProperty(p)) {
if(new Date(p) >= new Date(startdate) && new Date(p) <= new Date(enddate)) {
total += parseInt(arr[p], 10);
}
}
}
console.log(total);
Sample http://jsbin.com/imUdewaJ/1/edit
I'm sure there is a better way to do this, but I don't know how due to having to parse the date object out for comparison.
--Edit added in the hasOwnProperty check from comments below
When doing stuff with dates, you might want to use thirdparty tools to handle browser compatibility. Momentjs is a good one for dates.
solution with momentjs:
var startdate = moment('2014-01-03');
var enddate = moment('2014-01-05');
var obj = {};
obj['2014-01-02'] = '2';
obj['2014-01-03'] = '3';
obj['2014-01-04'] = '4';
obj['2014-01-05'] = '5';
obj['2014-01-06'] = '6';
var strDate;
var total = 0;
for (strDate in obj) {
if (obj.hasOwnProperty(strDate)) {
var date = moment(strDate)
if (date.diff(startdate, 'days')>=0 && date.diff(enddate, 'days')<=0) {
total += parseInt(obj[strDate], 10);
}
}
}
console.log(total);
It's possible that some browsers won't support date1 > date2, so it might be better to also use getTime().
function getDate(date) {
return new Date(date).getTime();
}
function getTotal(start, end) {
var total = 0;
for (var k in obj) {
var current = getDate(k);
if (current >= start && current <= end) {
total += parseInt(obj[k], 10);
}
}
return total;
}
var start = getDate(startdate);
var end = getDate(enddate);
console.log(getTotal(start, end)); // 12

Get records for a particular hour and an average of corresponding data

I call a webservice and get data. The data is in the format -
mail: "xyz#xyz.com"
price: "9.5"
name: "xyz"
receiveddate: "1374484561920"
I convert the date in millis to date and find the hour in which price was something. So eachEntryDate has the hour i.e 11, 12, 13 etc.
for(var l=0; l<data.length; l++){
var dataDate = recs[l].receiveddate;
dataDate = +dataDate;
var eachEntryDate = new Date(+dataDate.toString());
eachEntryDate = eachEntryDate.toString();
eachEntryDate = parseInt(eachEntryDate.substr(16, 2));
hourlyRecs[l] = {hour:eachEntryDate, price:recs[l].price};
}
Now i want to get the average of the price for each hour. i.e. the average of the price where the hour is 11,12 etc. The data is in a random order. What is the best way to do this?
You could accomplish with this:
hourlyRecs.sort(function(a,b) { return a.hour - b.hour; } );
var results = [];
var value = {};
var sum = 0;
var count = 0;
var hour = hourlyRecs[0].hour;
for(var i = 0; i < hourlyRecs.length; i++) {
if (hourlyRecs[i].hour == hour) {
sum += hourlyRecs[i].price;
count++;
}
else {
value.avg = sum / count;
value.hour = hourlyRecs[i].hour;
results.push(value);
value = {};
sum = 0;
count = 0;
sum += hourlyRecs[i].price;
count++;
}
}
value.avg = sum / count;
value.hour = hourlyRecs[i].hour;
results.push(value);
You would end up with an array of hour/avgPrice.
Hope it helps
Create an array which will hold all the prices per hour.
JavaScript
/* Fill an array by hour, containing all the prices for that hour */
var average = [];
for (var elem in hourlyRecs) {
average[hourlyRecs[elem].hour].push(hourlyRecs[elem].price);
}
/* get the average per each hour*/
for (var hour in average) {
var priceAverage = 0;
var count = 0;
for (var price in average[hour]) {
priceAverage += average[hour][price];
count+=1;
}
average[hour]["priceAverage"] = parseFloat(priceAverage/count,10);
}
Average for hour #11: average[11]["priceAverage"].
Alright. Since everything has to be done in JS, let's organize the data first.
Create 2 arrays with 24 elements - one for cost at each hour and one for counts. (or just one holding 2 values)
As you loop through the data, increase the relevant cost at each time and bump up the count.
Something like this:
var counts = [];
var costs = [];
for(var i = 0; i < recs.length; i++) {
// This is your current code
var dataDate = recs[l].receiveddate;
dataDate = +dataDate;
var hour = new Date(+dataDate.toString());
hour = hour .toString();
hour = parseInt(hour .substr(16, 2));
// Extend it with this
counts[hour]++;
costs[hour] += recs[l].price;
}
And then just divide the cost by count and thee you go. This way you don't have to worry about sorting the data or anything like that.
Also, your hour picking function can be simplified if you just divide the numebr of milliseconds by 3600000 - the number of mills in 1 hour and take the int out of it.
hour = parseInt(milliseconds / 3600000);

Categories

Resources