Is it good practice to surround code with braces? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Is it okay to surround code with braces { } for making code in IDE's compress/collapse?
For example:
{
function foo(a,b) {
return a*b+b;
}
function bar(a,b,c) {
return a*b+c;
}
}
This would collapse in my IDE to the following:
{ ...
}
Are these extra braces allowed, or would it be syntactically incorrect? (I know it works because the code has run without any errors regarding syntax.)

You've already answered your question:
Are these extra braces allowed, or would it be syntactically incorrect?
with
(I know it works because the code has run without any errors regarding syntax)
It is syntactically permitted, as of ES2015.
But, these sorts of plain blocks have some issues:
Function declarations inside them work very strangely (so using them is likely to confuse people in some circumstances)
They're quite unusual to see - generally, script-writers do not use them, and do not expect them, so using such a block is likely to confuse some
If you need the ability to "compress" code - to group parts of related code without cluttering up a script - consider using modules instead. For example
// fooAndBar.js
export function foo(a, b) {
return a*b+b;
}
export function bar(a, b, c) {
return a*b+c;
}
Then just import the functions when needed.
It's a lot easier to maintain and debug 8 files that are 50 lines each than it is to do the same for one file that's 400 lines each. If you have to collapse blocks to make something easier to read, it's probably time to refactor to another file.

Related

Why use a while loop for a game loop? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Just wondering, is there a specific reason to use a while loop as the game loop. Or could I use another method, like this one.
Note: this is not proper code, and has not been tested. This is just a general idea. This example is also not consistent to a specific coding language, but may follow mostly JavaScript because that's the coding language I know off the top of my head. I've actually tried something similar to this in dart (google flutter).
var startTime;
var running = false;
function loop1(){
startTime = system.currentMillis();
loop2();
}
loop2(){
gameUpdate();
//ignore my math, I did not focus on doing that property
//this is just an example and is not proper math
var delay = 1000 / (system.currentMillis() - startTime);
setTimeout(loop3, delay);
}
loop3(){
if(running){
loop1();
}
}
edit: could using something like this to avoid the need to use sleep(); be helpful to performance? (or phone battery)
It is perfectly possible to use your code as a main game loop. The reason why a while is preferred is because a main game loop executes endlessly until aborted, this is done simply with while (true) and aborting somewhere inside with break, or with while (abort == false) and setting abort = true somewhere inside. Notice that other loop variants such as for and do-while are more verbose, unless your language let's you do for (;;). Also note that you can restructure your proposed loop to a more simpler version using a while loop.

Is it bad to have If-instanceof-statements in Typescript? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
selectAction: (actionEvent) => {
if (actionEvent instanceof Action1) {
// action1 body implementation
} else if (actionEvent instanceof Action2) {
// action2 body implementation
}
}
The above code snippet reflects that different types of action which does different functionalities.I have used if and else condition to check action.
I feel it's not a good solution since I might have more actions in the future and my if-else-ladder will keep growing and I need to update my code again when there is a change.
Any idea on improving this specific scenario?
Use the approach of duck typing to avoid conditional scenarios. Source
Have a method called selection() inside each type instance Action1 and Action2 so- on and use that to define the body/desired functionality you want to build. And simply call selection() method avoiding condition. So based on the instance of the type it will call the correct selection() method of the corresponding type
There's nothing inherently wrong with using if/else in TypeScript.
However, when you're using instanceof, the odds are that you probably have a better option available. In this case, almost certainly, the actions themselves should be responsible for doing what they do:
selectAction: (actionEvent) => {
actionEvent.execute();
}
...or
selectAction: (actionEvent) => {
const action = /*...derive action from actionEvent...*/;
action.execute();
}
...or similar (or of course, use actionEvent.execute() directly instead of selectAction).
This is fundamentaly polymorphism, having different objects conforming to the same interface, and doing (potentially) different things when called.

Why this for loop on Javascript is worse than pattern matching? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I needed to create a lot of entities in arrays at my job, and some guy said to me use this library to use "pattern matching" in my pull request instead creating manually the arrays an populating it.
We have to create a lot of things, eg. of user:
function createUser(id){
return {
id: id
}
}
var users = createStuff(createUser, 50);
what I did to populate:
function createStuff(createFunction, howManyTimes){
var createdStuffs = [];
for(var i = 0; i < howManyTimes; i++){
createdStuffs.push(createFunction(i));
}
return createdStuffs;
}
what he asked me to do with pattern matching:
function createStuff(createFunction, howManyTimes){
return howManyTimes.matches(
(x = 0) => [],
(x) => [createFunction(x)].concat(createStuff(createFunction, x - 1))
)
}
What is the benefits about this pattern matching? I do understand the recursive calling on his example which replaces the for loop, but I think my example is easier to read though all the creation logic is basically written at a single line at his example.
I'm asking explanations about this and most people are telling me "it's better because is functional and have less moving parts", is this really true? I don't agree with him and I'd like explanations or arguments to tell he's wrong
Your colleague has taken the quite correct premise that immutability and a functional style is beneficial and drawn a very incorrect conclusion that any immutable solution employing a functional style is superior. Readability is important and possible in any paradigm.
A proper functional solution using underscore.js with all the benefits and none of the eye-gouging readability issues would look like:
var users = _.map(_.range(howManyTimes), createUser);

how to deobfuscate javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
can any one tell me how to de-obfuscate this?
É=-~-~[],ó=-~É,Ë=É<<É,þ=Ë+~[];Ì=(ó-ó)[Û=(''+{})[É+ó]+(''+{})[ó-É]+([].ó+'')[ó-É]+(!!''+'')[ó]+({}+'')[ó+ó]+(!''+'')[ó-É]+(!''+'')[É]+(''+{})[É+ó]+({}+'')[ó+ó]+(''+{})[ó-É]+(!''+'')[ó-É]][Û];Ì(Ì((!''+'')[ó-É]+(!''+'')[ó]+(!''+'')[ó-ó]+(!''+'')[É]+((!''+''))[ó-É]+([].$+'')[ó-É]+'\''+''+'\\'+(... Masked for confidentiality reasons
Look for the "()" in the end. Those are for executing the obscured function code. If you remove the last one and use "toString()" instead in node you will get the following (After formatting a bit):
function anonymous() {
na = prompt('Entrez le mot de passe');
if(a == 'I changed this to not make it too easy for you' {
alert('bravo');
} else {
alert('fail...');
}
}
Try it yourself, but always be careful, since if you are not careful this kind of code can run harmful stuff on your computer.
PS: A few more words about how it actually works. Those weird french seeming letters everywhere are just variables, which are defined in the beginning. É for example has the value of 2, since using the bitwise not operator on an empty array results a -1, and -~-(-1) = 2. All those backslashes are then used in combination with this numeric variables to get characters which eventually form the code of the function.

Is this eval Evil? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Writing a function in JavaScript. The plan is the function creates an object, which requires boolean statements as parameters. Something like this ->
var foo = new fuzz("pie < squirrel", "monkey === banana");
My question is - Is this evil?
*Note - * Inside the function 'fuzz' I will run checks on the values of the parameters. (Check string.length etc). I think this is how one is meant to use eval, it just has such a bad reputation on t'up web.
Thanks
Summing up the conclusions in the comments: write a simple rule evaluation engine! E.g.:
var variables = { ... };
function niceEval(condition) {
var operands = condition.match(/(\w+)\s+(\S+)\s+(\w+)/);
switch (operands[2]) {
case '<' :
return variables[operands[1]] < variables[operands[3]];
...
}
}
This also gives you a lot more control over possibly occurring errors than blindly evaling a string.

Categories

Resources