Strange javascript assignment - javascript

I've worked with C# for many years but I'm pretty inexperienced when it comes to javascript so this should be an easy pick for any of you javascript wizards. I was looking through a JQuery plugin for managing cookies (https://github.com/carhartl/jquery-cookie) when I saw these two lines:
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
I just want to make sure I understand this correctly; is this the equivalent of:
var days = options.expires;
options.expires = new Date();
var t = options.expires;
t.setDate(t.getDate() + days);
I imagine this is an attempt to compress the code as much as possible but I admit I get confused when thinking about what the value of the variables are. Especially since options.expires can be either a javascript date object or a number of days.

Yes. The return value of an assignment is the value that was assigned.

Related

Cypress API testing - Using custom commands to return a value to avoid duplicating code

First of all. I'm purposely re-learning JS/Cypress and I'm purposely starting from bedrock again, so apologies in advance.
I'm currently using Cypress for REST API testing. I am migrating tests over from an existing Ruby/Selenium framework and I want to use something similar to writing Ruby functions to clean up my code, as I am currently duplicating code.
An example:
I have a block of code that generates a date, 365 days in the past (ISOString used for a reason, in this case)
var date = new Date();
date.setDate(date.getDate() - 365)
var minDate = date.toISOString().split('T')[0]
I want to do something like
Cypress.Command.add('dateGen', () => {
var date = new Date();
date.setDate(date.getDate() - 365)
var minDate = date.toISOString().split('T')[0]
})
and call it in. In this case, I would want to call it in to my test using something like
(excuse the incorrect syntax, I'm just doing it as a like for like (Ruby/JS) illustration):
var date = cy.dateGen
However, running this in any js/cypress friendly combination falls over as Commands do not return values.
I am already set up to use commands in index.js etc, so that bit isn't causing me any problems. I am already using commands for things that don't return a value, so I know I'm doing that bit correctly.
I sorted it using the following:
Cypress.Commands.add('dateGenerator', (days) => {
var newDate = new Date();
newDate.setDate(newDate.getDate() - days)
var date = newDate.toISOString().split('T')[0]
return date
})
and then called it via
cy.dateGenerator(noOfDays)
.then((date) => {
var minDate = date
}
The bit I was missing was the
return date and I was closing the blocks off too early in my test code.

Convert Javascript Date object to Filetime

Can't believe I'm unable to find the very simple case of converting a Javascript date object to Filetime.
The other way around popped up a lot while searching.
I have provided the solution below for anyone else who is looking for it.
To convert now to Filetime:
function filetimeFromDate(date) {
return date.getTime() * 1e4 + 116444736e9;
}
const now = new Date();
const filetimeNow = filetimeFromDate(now);
console.log(filetimeNow);

SharePoint/Javascript: comparing calendar date times in javascript

I am trying to find the best approach to comparing date/times using Javascript in order to prevent double booking on a SharePoint calendar. So I load an array with items that contain each event, including their start date/time and end date/time. I want to compare the start date/time and end date/time against the start/end date/times in the object, but I am not sure how to ensure that dates will not lapse.
like:
//date that is created from user controls
var startDate = new Date(startDat + 'T' + startHour + ':' + startMin + ':00');
var endDate = new Date(endDat+ 'T' + endHour+ ':' + endMin+ ':00');
for ( var i = 0; i < allEvents.length; i++ ) {
var thisEvent = allevents[i];
//having trouble with the compare
//i have tried silly ifs like
if (thisEvent.startDate >= startDate && thisEvent.endDate <= endDate) {
// this seems like I am going down the wrong path for sure
}
}
I then tried breaking apart the loaded object into seperate values (int) for each component of the date
var thisObj = { startMonth: returnMonth(startDate), startDay: returnDay(startDate), etc
but I am not sure this isn't just another silly approach and there is another that just makes more sense as I am just learning this.
I have a similar requirement in progress but chose to solve it at the booking stage, with jQuery/SPServices.
The code is still in build (ie not finished) but the method may help.
I attach an event handler to a column, then on selection, fetch all the dates booked in the same list to an array, then display that array on a rolling 12 month cal, as below.
I'm not checking to ensure a new booking doesn't overlap but a quick scan through the array on Pre-Save would provide a strict Go/No Go option for me. Relies on client side JS though, so not going to work in a datasheet or web services context.

JavaScript todays date + x, bad practice?

I'm currently working on a project that makes heavy use of dates.
Is there anything inherently wrong with doing this:
var TodayPlusSeven = new Date(new Date().setDate(new Date().getDate() + 7));
I'm not an expert with JavaScript, but this seems to work. I'm not sure of the negative effects that doing something like this can have.
Thanks.
In your current code you create 3 Date objects in the process. This is not necessary. You could just update one object to the respective day:
var TodayPlusSeven = new Date();
TodayPlusSeven.setDate( TodayPlusSeven.getDate() + 7 );

Javascript prototype function: decimal time value to a time string

On a project I'm currently working on in JavaScript, I'm using decimal formats so it's easier to calculate with rather than using an hour/minute format in strings (calendar related project). To display the time on the user's screen though, the timecode has to be shown as hh:mm.
I thought it would be great to use a String prototype function for this as it would allow me to use code like:
var time = 8.75;
document.write("Meeting at "+time.toTime()); // writes: Meeting at 8:45
So far, I've got that almost working, using:
String.prototype.toTime = function(){
var hrs = this.toString().slice(0,this.indexOf("."));
var min = Math.round(this.toString().slice(this.indexOf("."))/100*60);
min = min<10 ? "0"+min : min.toString();
return hrs+":"+min;
}
The problem, though, is that this will only work if the variable time is a string. Otherwise it will give an undefined error.
Would there be any way of applying the prototype to a different object in JavaScript, so that I don't have to use time.toString().toTime()?
Thanks!
Firstly, you can add to the Number prototype. Many people will warn against modifying prototypes, which in many cases is justified. If there is a chance 3rd party scripts will be running alongside yours, it is a danger to modify prototypes.
Secondly, I simplified your code a little, using modulus, and floor to calculate the hrs and mins...
Number.prototype.toTime = function(){
var hrs = Math.floor(this)
var min = Math.round(this%1*60)
min = min<10 ? "0"+min : min.toString();
return hrs+":"+min;
}
var time = 8.25;
console.log("Meeting at "+time.toTime());
You can use Object.prototype.toTime.

Categories

Resources