Javascript ENUM pattern naming convention - javascript

I am working on a javascript project which requires use of javascript "Enums" meaning Objects like:
var WinnerEnum = {
Player1: 1,
Player2: 2,
Draw: 0
};
This is working great for me, however, I have no idea what is the proper way (according to convention) to name the Enum because as far as I know only class names start with a capital letter (indicating the ability to call a constructor on).
JSHint also outputs the following warning:
Missing 'new' prefix when invoking a constructor.
If there is no convention, I would appreciate a good way to name enums that would not confuse them with class names. Update 2014 : JSHint no longer does this.

That is indeed the correct way to name the enum, but the enum values should be ALL_CAPS instead of UpperCamelCase, like this:
var WinnerEnum = {
PLAYER_1: 1,
PLAYER_2: 2,
DRAW: 0
};
This is similar to Java's naming convention for enums.
Some references:
Google JavaScript Style Guide
Stijn de Witt's Blog
Enumify documentation
As with coding style in general, you'll find people doing things in many different ways, with each way having its own set of good reason. To make things easiest for anyone reading and working with your code, however, I would recommend using the style which has the most authoritative reference and therefore usually the most widespread adoption.
I couldn't find any reference more authoritative than Google's style guide and the writings above, written by people who have given some serious thought to enums, but I'd be interested to hear of any better references.

According to Google's coding conventions this is the correct way indeed to name an enum in javascript.
As requested here is a link.

First, there is no "correct" way* of declaring a pseudo-enum in JS. You should strive to be consistent within your existing code base and/or your organization's conventions if possible.
One popular convention is Google JavaScript Style Guide. E.g.:
const TemperatureScale = {
CELSIUS: 'celsius',
FAHRENHEIT: 'fahrenheit',
};
Curiously, this is inconsistent with MDN's hidden convention for const, as in Google's example, TemperatureScale is a const and TemperatureScale.CELSIUS is not!
* it must be a valid JavaScript identifier.

Related

How can I distinguish typescript from javascript by looking at the source code?

I am inspecting some code on Github and I need to quickly understand if the script is javascript or typescript.
Are there any easy shortcuts or clues to this?
As an example, in this image from https://www.typescriptlang.org/ gives me a clue that if an array is declared with a bracket [] after the variable name, then it is typescript.
You can distinguish between the two formats by looking simply at the functions.
Are any of the functions specifying types such as 'string,integer,object,array,function?...' etc?
In traditionally javascript this is not allowed.
Best,
AT
Also as others may have pointed out, you can also check the file extension

How to get jsdoc generation for parms of class methods that use arrow functions?

I'm a student who's capstone project/work intergrated learning is about to end. I'm working on producing technical documentation to hand off to the next team that will continue on with this work, but I've hit a snag.
My class methods that use arrow functions aren't generating params documentation when I create documentation using the jsdoc tool.
i.e.:
becomes
The documentation works as intended in visual studio code/intellisense:
I've been googling around to try and figure out what the problem was, but I failed to find anything.
I mean, my research yielded:
Outdated way to make vscode play nice with arrow function
syntax: (https://github.com/Microsoft/vscode/issues/36283) (https://github.com/Microsoft/vscode/issues/22264) ((This one is the actual issue where the support was added) https://github.com/microsoft/TypeScript/issues/14134)
Outdated info on the jsdoc support for this feature:
https://github.com/jsdoc/jsdoc/issues/1310
etc., etc., again, nothing useful.
Of note is that I'm using the jsdoc-export-default-interop plugin so that jsdoc will actually generate things for export default [CLASS OR FUNCTION].
I've found a solution that fits my requirements
However, while it is good enough for my purposes, I'm not entirely sure it's acurate and would be happy to hear critisims, other people's viewpoints and solutions. I'll explain the concerns I have at the end.
The problem: It looks like jsdoc cannot automatically detect if a member assignment is a function when parsing.
I have no idea why VSCode is able to detect it automatically, but it appears the JSDoc tool cannot. Here it is stated in the official documentation
Link to documentation: (https://jsdoc.app/tags-function.html)
The solution: Document the member with the #function tag (or an alias like #method).
By documenting the class member with the #function tag like so:
I am able to get the arrow function to generate as a class method, and get params documentation:
My concerns
Well the biggest concern/annoyance is now I need to go through all the source code and add a bunch of #function tags. Ah whelp.
Other concerns are that I may have misunderstood the problem/I'm not quite sure if this is best practice.
And I'm not too certain if this documentation is accurate in terms of if there is actually a tangible difference between a class member arrow function and a class method that I need to capture in the API documentation.
Anyway, I think this will be what I go with, but I'll be monitoring this answer to read any input/feedback :)

Are good practices regarding usage of hardcoded strings different for Javascript

I recently started learning and using JavaScript with Node.js. One of the things I noted, in different tutorials and also in production code, is that there are lots of hardcoded strings.
For example: https://www.tutorialspoint.com/nodejs/nodejs_event_emitter.htm
Same applies for production code - using strings for eventNames, property name, different status values, etc. It makes it harder to follow through existing code.
Is there any good reason not to use patterns like this for example?
var Events = {GoodEvent: 'goodEvent', BadEvent: 'badEvent'};
myObject.on(Events.GoodEvent, func)

Generate object from Typescript interface

I realize this is essentially the opposite intent of Typescript, but I would like to be able to programmatically generate an object FROM a typescript interface. Basically, I want something like this:
interface Foo {
bar: string
}
const generateObjFromInterface = (Foo) => // { bar: 'string'}
I -do not- mind how contrived the implementation is if it IS possible! If it is categorically impossible that would also be helpful information!
Thanks in advance!
It is possible. As typescript 2.4 is around the corner we can use custom transformers for typescript during compilation and get the list of all properties that are there and as a result create object with such properties.
Here is an example, but please note - as I have said this require to use typescript 2.4+ that is not yet in stable release
Since TypeScript's interfaces are not present in the JavaScript output, runtime reflection over an interface is impossible.
Given this TypeScript:
interface Foo {
bar: string
}
This is the resultant JavaScript:
Since there is no JavaScript, what you want to do is categorically impossible is very contrived.
Edit: Come to think of it, you could find, read, and parse the *.ts source file at runtime.
I also was searching for something that could do it and I didn't find anything. So I build this lib https://www.npmjs.com/package/class-validator-mocker, which can generate random data for classes attributes annotated with class-validator's decorators. Worked pretty well for my purposes.
I did it by using intermock (Google)
Here is a demo page

Big super happy javascript compression

Now, I've heard of javascript compressors, used a bunch and favour a few. However, they all do the same thing. Remove unnecessary space. That's great, they do exactly what it says on the tin. Compresses Javascript. However, looking through some of the major players that provide legendary libraries (such as jQuery), they offer "minified" sources that are entirely unreadable. Notably, the variable names change from someThingLikeThis to c. This is compression that I cannot seem to find anywhere.
My question is, where can I find a Javascript compressor which compresses variables in addition to removing unnecessary space. Or is it done manually?
For example:
// My Javascript:;
var cats = 'Nyan',
dogs = 'Hound';
alert(cats + dogs);
// jQuery styled compression:
var a='Nyan',b='Hound';alert(a+b);
As far as i know http://developer.yahoo.com/yui/compressor/ Does what you need :)
That should be done by a standard minifier. If it is not, then most likely the variable names just cannot be renamed safely (global variables/functions).
Also what you might be looking for is obfuscator. Check this question:
How can I obfuscate (protect) JavaScript?
Google Closure Compiler is the most advanced tool to transpile/minify JavaScript code.
It basically features two compilation levels—simple and advanced. You can use the simple compilation level on pretty much any JS code.
The true magic is in the advanced level which removes unused code, inlines functions, flattens properties (abc.def.ghi -> a) and renames all custom variables. But you have to write the code in a way the compiler can understand.
If you're serious about JS, read the "Closure: The Definitive Guide" by Michael Bolin who is one of the lead developers of the Closure Tools.

Categories

Resources