compile time required function parameter checking - javascript

Is there a best practice way of enforcing parameters in functions at build time vs runtime? For example if i have following function:
function localize(strings, key, ...args) {
return ...
}
and I called it as such:
var result = localize('myKey')
I did not pass the first parameter ('strings'). I would like to throw a compile error and not wait until runtime to get the error.

Because Javascript is not compiled, and dynamically typed, there is no way to enforce the contract in your example except at runtime.
However, you can use a build system like Typescript, Flow, etc, to add type annotations to your code. These require a compilation step BUT the issue you have in your example would be caught by both during that step.
Without that, there is no way to get what you want as far as I know. The best you could do in vanilla javascript is to validate the arguments you are given inside the localize function, and use logs/errors so that you can easily identify the issue when you test your code locally. The important bit here is that without actually running your code, there is no way to catch the error in your example using vanilla JS.

Related

How to access flow variables from javascript in power automate

I'm working on a power automate flow and I'm having some trouble. I copied some text to my clipboard in the flow and i asigned it to a variable in my flow. I'm trying to parse the variable using the javascript scripting feature but i'm getting a syntax error whenever I try to use the %variable% syntax in javascript. I used the variable button in the text editor they give you to add the variable to my script but even something simple as var res = %SimResults%; returns an error C:\Users\$me\AppData\Local\Temp\Robin\nkwrgcdoxrp.tmp(1, 11) Microsoft JScript compilation error: Syntax error
It seems that even though I Should be able to access my flow variables from Javascript it throws a syntax error when I try
You'll need to put quotes around it ...
var res = "%SimResults%"
... it treats the variables as more of a find and replace within your Javascript code, therefore, you need to do the work to ensure the correct encapsulation, etc. exists.
This may not solve your problem though depending on the complexity of what is contained within the variable.
If you have additional quotes, etc. you may need to escape them prior to putting them in the Javascript task IF they exist within the string ... just be mindful of that.

TS: How to get interface from a dynamically created object

I have a schema object that contains the typed property that starts empty.
const schema = {
typed: {},
// ...
}
schema.typed will be filled dynamically when the application starts, example
typed['name'] = 'Yung Silva'
typed['age'] = 22
in another moment
typed['facebook'] = 'fb.com/yungsilva'
typed['whatsapp'] = 81981355509
there is no pattern, really each time the application is started it will be a totally different and random structure.
I would like to get an interface for this object that was dynamically assembled, example
type Fields = typeof schema.typed
it is possible?
is disturbing me at the beginning, at the moment to create the object dynamically, I don’t know what type to define for schema.typed
This is not possible since Typescript "checks" your types at compile time.
"The goal of TypeScript is to help catch mistakes early (before running the code, at compile time) through a type system and to make JavaScript development more efficient." more
At runtime the code that runs is a normal (sorta) javascript code.
there are several libraries (typescript-is) that can help you check types at run time, but the common use case doesn't need them.
TypeScript is about type checking ahead of runtime. Its purpose is to check the code consistency with itself and the third party library it uses, before running it. TypeScript won't be able to assign a type depending on the actual data, because it simply doesn't exist anymore at run time. When you write will be a totally different and random structure that means you're using plain JavaScript and its dynamic nature, so if your data never has common parts, just don't type it at all (or as any).

How to test small snippets of javascript code without a web browser?

I am trying to teach beginners javascript. Here is what I am trying to do:
I will give them a snippet of code such as a function with something incorrect:
const square = function(x) {
return x + x; // Wrong! This will double the number, not square them.
};
They will submit the code back to me.
I would like to write some test cases which would run on their code and evaluate if they are correct.
Does it make sense for them to submit their code as js files, and then I have a node.js project which reads their files and passes values to their functions and tests the response ?
Or does it make more sense to use a unit testing framework like mocha and chai etc ?
Both options would work, i.e Node directly or a test framework with test suites on their machines.
If you really want to get all their submissions and evaluate them on your own, you can simply ask them to export a function with a predefined name, in this case of this square exercise, it could be export function square { ..., then you add all those files to a folder, list all them using the fs module with something like fs.readdir/fs.readdirSync and dynamically call require on each file and execute the square function.
Note that this approach means you'll be running untrusted code on your machine, e.g one could potentially delete a file on your system (or actually do everything else possible with the privileges you execute the program). But you suggested that it's a beginner class and it looks like you know everyone, so that approach may be acceptable and in that manner, you don't have to send test cases for everyone and teach them how to run them (although it would be good at some point to do so).

What's the best way to handle Eclipse errors on CouchDB Map/Reduce JavaScript functions?

As noted in Where to write and store mongoDB map/reduce functions in java project - Eclipse doesn't like a JavaScript (.js) file to only contain the following:
function(doc) {
if(doc.somekey) emit(doc._id, doc);
}
The keyword function is marked with an error:
Syntax error on token "function", Identifier expected after this token
This form is used in MapReduce, but perhaps it's not exactly valid JavaScript (I'm not a lawyer). Is there any way to allow this form?
edit it looks like it's a function expression instead of a function statement. ( MDN, ECMA-262 )
Non-solution: "Just add a function name" according to https://stackoverflow.com/a/11258388/185799 it seems that it's not important to economize on the size of these functions. However, adding a function name results in: {"error":"compilation_error","reason":"Compilation of the map function in the 'myView' view failed: Expression does not eval to a function."}
Possible solution? Add a function name or "module.exports = " at the top, and then remove it during a build phase, using grunt/gulp/yeoman or something related.
For now, what I am actually doing is using the literal form function anonymous(... and then doing a string replace just before calling synchronizeWithDb() to replace function anonymous( with function(. This doesn't answer my question, but works around it.
You have three bad options:
You can ignore the error since CouchDB can process this file (it will wrap it later to make it valid).
You can change the file extension but then you lose syntax highlight, code completion and error checks.
You can delete the error in the error view. It will stay deleted until you change the file the next time or you do a full build.
You may be able to configure Eclipse to stop validating the file.
There are two ways to implement #4:
You can ignore the resource. That makes this file invisible to Eclipse and all plugins. Which means you can't edit it anymore inside of Eclipse. Use Resource Filters for that.
You can check the per-project preferences for Validation rules for JavaScript. Maybe you can exclude the file.

Flow type annotations and valid JavaScript source

I'm playing with Facebook's new Flow Type checking system.
In Flow, meet Underscore it appears that they change this JavaScript code
var root = this;
into this
var root: any = this;
But this is no longer valid JavaScript, right? I understand why external Interface files would be useful, but how are type annotations added directly into valid JavaScript sources?
Previously, Google Closure compiler and other projects used on JS comments.
As of Flow 0.4.0 you are able to put the Flow syntax into the comments. This solves your issue. So your example would look like:
var root/*: any*/ = this;
This results in valid JavaScript syntax and there is no need to transpile your code.
Further details can be found here:
http://flowtype.org/blog/2015/02/20/Flow-Comments.html
You're right, that code is no longer valid javascript. That means that when you use Flow in someJavascriptFile.js, you have to execute a program that removes the Flow code from someJavascriptFile.js, which is called transpiling. Which transpiler to use depends on how you're running javascript, and will probably change over time, so I won't link to any.
You can also wrap the flow types into a comment, eg. var name /*:string*/ = "Hello flow.", which is valid javascript, but makes the code harder to read in my opinion.
In theory, Javascript engines could one day natively support Flow parsing, but that's a long ways off.
I missed Running Flow code where it discusses adding a build step to remove type annotations.
You can use the JSX transform tool (part of the React tools) to
translate your files to plain JavaScript
I also found flow-typestrip which is alternative.
I like external interface files per module better, as you can avoid introducing a build step.

Categories

Resources