Append a parameter to an array and evaluate each array element - javascript

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.

Related

Generate random string every 24 hours then refresh 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>

Find the closest hour [javascript]

I have a list of these items:
hours = ['19:30', '20:10', '20:30', '21:00', '22:00']
Assuming that now it's 20:18, how can I get the '20:10' item from the list? I want to use this to find the currently running show in a TV Guide.
First we should parse it to datetime in some way:
function parseTime(str) {
var values = str.split(':');
var hour = parseInt(values[0]);
var minutes = parseInt(values[1]);
var d = new Date();
d.setHours(hour);
d.setMinutes(minutes);
return d;
}
var now = new Date();
var bestMatch = undefined;
var bestMatchDiff = undefined;
And finally:
for(var i=0; i<hours.length; i++) {
var parsedTime = parseTime(hours[i]);
var diff = Math.abs(now - parsedTime);
if (!bestMatchDiff || bestMatchDiff>diff) {
bestMatch = parsedTime;
bestMatchDiff = diff;
}
}
bestMatch would be the closest time. This is not the currently running show now. For that, you need to ignore times that are yet to come:
for(var i=0; i<hours.length; i++) {
var parsedTime = parseTime(hours[i]);
var diff = Math.abs(now - parsedTime);
if (now<parsedTime) {
continue;
}
if (!bestMatchDiff || bestMatchDiff>diff) {
bestMatch = parsedTime;
bestMatchDiff = diff;
}
}
But keep in mind this might return undefined even if your list is not empty.
var hours = ['19:30', '20:10', '20:30', '21:00', '22:00']
var diffrenceTime
var selectedShow
var d1 = new Date()
var currentHH = 20
var currentMM = 18
d1.setHours(currentHH, currentMM, 0)
hours.forEach(v => {
var d2 = new Date()
var hh = v.split(':')[0]
var mm = v.split(':')[1]
d2.setHours(hh, mm, 0)
if (diffrenceTime == undefined) {
diffrenceTime = d2 - d1
selectedShow = v
}
if (d2 - d1 < 0 && d2 - d1 >= diffrenceTime) {
diffrenceTime = d2 - d1
selectedShow = v
}
})
console.log(selectedShow)
To find the currently running show (of course more validations need to be added):
const currentShow = hours[
hours.findIndex(
(c) => new Date(`01/01/2000 ${c}`) - new Date(`01/01/2000 20:31`) >= 0
) - 1
];
To find the next show:
const nextShow = hours.find(
(c) => new Date(`01/01/2000 ${c}`) - new Date(`01/01/2000 20:31`) >= 0
);
Well, you could do something like this
var originalArray = ['19:30', '20:10', '20:30', '21:00', '22:00'];
var newArray = originalArray.map(i=>{
return i.split(":")
})
newArray.forEach((k, idx)=>{newArray[idx] = parseInt(k[0]) + parseInt(k[1])/60})
console.log(newArray);
var time = "20:18".split(':');
var t = parseInt(time[0])+ parseInt(time[1])/60;
console.log(t);
var closestTimeIndex = 0, closestDistance = Math.abs(t-newArray[closestTimeIndex]);
for(var m=1; m<newArray.length;m++){
if(Math.abs(newArray[m]-t) < closestDistance){
closestDistance = Math.abs(newArray[m]-t);
closestTimeIndex = m;
}
}
console.log("colsest time is: " + originalArray[closestTimeIndex]);

Javascript in googlespreadsheets

I am trying to create a counter that counts the cells that include in their content the date before today as a date. However the result in cell 16,1 is always zero as it seems that my loop does not work. I know I can do it with a formula in spreadsheets but I want to use javascript. Also I am trying to find out what is wrong in MY code.
I have wrirtten the following lines of code:
function job_counter() {
var yesterday_jobs=0;
var ss=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var e = new Date(new Date().getFullYear(),new Date().getMonth() , new Date().getDate())
var yesterday = new Date(new Date().getFullYear(),new Date().getMonth() , new Date().getDate())
yesterday.setDate(yesterday.getDate() - 1);
var range_unformated=ss.getRange(2,3,25).getValues()
var date;
for (var i=1; i<25; i++){
date=Date.parse(range_unformated[i])
Logger.log(date[3])
if ( date[i] - yesterday.getTime() >= 0 && date[i] != "" ){
yesterday_jobs = yesterday_jobs + 1
ss.getRange(16,2).setValue(yesterday_jobs)
}}
// check yesterday_jobs
}
This will solve your problem, it uses getValues getting a range of 24x24 cells and iterating it to compare every cell value to see if it is equal to yesterday:
function isYesterday(){
var yesterday_jobs=0;
var ss=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var row=0;
var col=0;
var date;
var yesterday = new Date(new Date().getFullYear(),new Date().getMonth() , new Date().getDate())
yesterday.setDate(yesterday.getDate() - 1);
range = ss.getRange(1,1,25,25).getValues()
for (var i = 0; i < 25; i++){
for ( var j = 0; j < 25; j++) {
date = Date.parse(range[i][j]);
if ( date - yesterday.getTime() <= (24 * 60 * 60 *1000) ){
yesterday_jobs = yesterday_jobs + 1;
}
}
}
ss.getRange(16,2).setValue(yesterday_jobs);
}
Things that were wrong...
This is wrong and it is the reason it's not working:
yesterday_jobs === yesterday_jobs + 1;
You should be doing:
yesterday_jobs = yesterday_jobs + 1
Why?
Because == and === are Comparison operators, and = is an assignment operator.
What you are trying to do is to set a new value to yesterday_jobs, not to compare it, so you have to use =.
This will solve your problems with the loop assignations.
When doing a = 2 you are assigning a value to a variable:
a value is now equal to 2 value
When doing a == 2 you are asking:
Is a equal to 2 in value?
When doing a === 2 you are asking
Is a equal to 2 in value and type?
The example below shows how to retrieve and log the items names and items numbers.
function logItemstInfo() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
for (var i = 0; i < data.length; i++) {
Logger.log('Items name: ' + data[i][0]);
Logger.log('Items number: ' + data[i][1]);
}
}

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

Categories

Resources