Dynamic typing in JavaScript: Is this a good idea? - javascript

I haven't done a lot of coding in dynamically typed languages such as JavaScript until recently, and now that I'm beginning to understand what's possible, I'm starting to wonder what's a good idea and what's not. Specifically, I am unsure as to whether changing the type of a variable as a function progresses through a sequence of operations is considered good practice.
For example, I have a bunch of files containing dates as strings. I'm using front-matter to extract date attributes and storing them within an object representing the original file. The strings themselves aren't very consistent, so I'm then using Moment.js to parse them, and storing the result back in the same attribute in the same object article.date. This feels more or less right to me, as article.date is only a String for one operation before being parsed and stored as a Date/'Moment' type.
The part I'm a little unsure of comes next. This is part of an ExpressJS app, and so an array of these objects is getting passed in as the data in a render() call, where it goes to a Jade template for rendering. But what if I want to use a display method in Moment.js to control the way the date looks as a String? Would it be reasonable to change the type of the date attribute back to a String again before passing it in?
Example:
articles[i] = processArticle(content);
// creates an article object from YAML, object has a property article.attributes.date
articles[i].attributes.date = moment(articles[i].attributes.date);
// attribute is now a Date/Moment
articles[i].attributes.date = articles[i].attributes.date.format("dddd, MMMM Do YYYY, h:mm:ss a");
// attribute is now "Sunday, February 14th 2010, 3:25:50 pm"

The reason why we even have type safety is to find errors in code early on: preventing invalid memory access/illegal operations/etc. In object orientated languages to allow decoupling and code re-use (polymorphism). Not just to make your life as a programmer more difficult, but to make sure your program will run.
Because JavaScript does not provide type safety, it's up to the programmer to do this. You will have to make sure that operations on a variable are valid and do not lead to an exception which stops your program from running. You will have to make sure that a method call can be invoked on any object.
So to answer your question: no, it's not a good practice to change the type of a variable as a function progresses.
To use Moment.js in your Jade template: How do I display todays date in Node.js Jade?

Related

How does JavaScript represent strings and Date objects in memory?

How does JavaScript represent strings and Date objects in memory?
Context and Intent
I'm mostly just curious, but here's what led to the question: We have code in our React front end that accepts JSON payloads from our API, and those payloads include dates -- in ISO-8601 UTC string form (e.g. 2023-02-01T17:01:08Z), of course.
As we pass the resulting model object around a variety of hooks, components, functions, etc., we keep it as a string, and we only parse it into a Date object if we are going to display it or use it to make decisions. In some cases, this means that we'll re-parse the same string into a Date multiple times in the course of rendering the UI. In other cases, we ignore the Date completely as it's not relevant for the page.
I'm trying to reason about whether it would be worthwhile to modify our system such that we always parse Date strings into actual Date objects upon receipt from our API. Our UI is written in TypeScript -- AFAIK this makes no difference with regard to my actual question -- and my biggest motivator in wanting to make this change is the improved type safety and clarity.
To be clear, time performance is the bigger concern, but I can do my own benchmarking. For the purposes of this question, I'm asking about memory performance, as much for my own understanding and education as for any technical decisions that might result, but I always try to understand the full scope of any tradeoff.
I imagine that this could be implementation dependent; if so, I'm most interested in the facts as they apply to modern versions of Google Chrome (with default configuration, if that matters), but happy to learn about other implementations as well.
Questions
If I take a 20-character ISO-8601 UTC string and parse it into a Date, how much memory would the resulting Date use? Does JavaScript work like Java, using an 8-byte "long" integer to store dates as milliseconds since the epoch? I found disappointingly little information about this in my searching; most of the results I found were actually about Java.
Also, how much memory does the string use? What's Javascript's internal string encoding? A quick Google indicates that it uses UTF-16 (and therefore 40 bytes for the 20-character date string)?
For both Date and String, are there any differences in applicable overhead? Are there optimizations that might apply to either Strings or Dates and affect the result (e.g. string interning -- which if I am understanding this correctly, JS does, but it would not apply to my use case since the value came from an API response)?

OpenTest Doesn't Take a Standard JS Date for the ReadEmailImap function

I am attempting to pass a value for sentAfter to org.opentest.ReadEmailImap function that contains a string formatted as YYYY:MM:DD HH:DD:MM per this documentation
The closest that I have come to this format is .toISOString(). ref
You can either build the date yourself using the JavaScript API, like here, or you can use a library like Moment.js (The moment.js file can be included in your test as described here). The first method is better for a quick and dirty, one time solution. The second is best if you have more advanced date/time logic that you need to execute.

How to Deal with String/Date Attributes in Angular

Which strategy do you guys use to deal with date attributes on your models which comes from json response on http requests ?
The Date attributes comes in string format and it troubles me when i'm using date components(like a Datepicker).
So, to fix this, usually I convert the String attribute into a date, like this:
person.birthday = new Date(person.birthday);
But it seems to be bad code. Besides, everytime I create a new date attribute I have to repeat the code above.
How do you guys deal with this situation ?
The simplest way I've found is to deal with dates as Timestamps.
This means you store a number, and when you request it, all you have to do is to make a
let d = new Date(myTS);
You can find some problems to that, such as the timezone depending on the client.
Otherwise, you can use Moment, which is made to deal with this kind of problem.

ASP.NET Razor C# to TypeScript/JavaScript equivalent for SqlDateTime

I'm working on converting an older .cshtml view file into pure HTML + TypeScript using Angular1. In this instance Angular really hasn't much to do with the issue as much as finding the equivalent functionality in TypeScript (or JavaScript) from some C# code within a Razor view.
The old code was the following:
ng-init="
vm.defaultStartDate='#SqlDateTime.MinValue.Value'; vm.defaultEndDate='#SqlDateTime.MaxValue.Value'"
In the updated code, these values will not be set in the view; there's no reason for that. The Angular controller logic written in TypeScript can initialize these values and use them when required. The problem is, I'm trying to figure out the equivelent code in TypeScript/JavaScript and I can't seem to come up with the correct implementation.
According to the MSDN, #SqlDateTime.MinValue.Value will equate to the following:
The minimum valid date for a SqlDateTime structure is January 1, 1753
And from the MSDN for #SqlDateTime.MaxValue.Value:
The maximum valid date for a SqlDateTime structure is December 31, 9999.
I've tried the following, but when executed I'm getting an issue on the server that the dates are not defined properly. When I debug in TypeScript they don't match the original versions either.
this.defaultStartDate = String(new Date('1/1/1753'));
this.defaultEndDate = String(new Date('12/31/9999'));
Certainly there is a better way I can initialize those dates and I'm sure I'm missing something trivial. What's the best way to set those dates using TypeScript/JavaScript to be essentially the bookend start/end default dates that the old C# code was doing?
Either convert you date to yyyy-mm-dd or client varient. You can refer to following link for the same.
Convert DateTime to string format("yyyyMMdd")

converting time using strtotime PHP

apologies this is probably a simple question - I am using php and JS to create a counter and I have stored a time using an SQL time field in my DB- I run a query to return this time but I now wish to convert this time into an integer, I assume I need to use the following, but I am lost on the syntax:
http://www.electrictoolbox.com/using-strtotime-with-php/
any help would be appreciated. many thanks in advance
It's hard to tell from your question what exactly you mean by "an SQL time field."
MySQL offers four kinds of time-like data types: TIMESTAMP, DATETIME, TIME, and DATE. To some extent it matters which one your table contains.
It's also hard to tell what you mean by "convert this time into an integer." Do you mean a UNIX-style timestamp (number of seconds since 1-Jan-1970 00:00:00 UTC)?
If that's the case you can get your database to do this conversion: use
SELECT UNIX_TIMESTAMP(value) ...
in your query. That will work for all the time-like datatypes except TIME. (Strange, eh? TIME means time of day with no date, so that's why it doesn't work.)
Otherwise, without more information it's hard to tell you how to use php to do this: we can't tell what your converting from and what you're converting to.

Categories