Promise all convention approaches [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 6 years ago.
Improve this question
we did some code review and it the code before was like following:
run: () =>{
var _this = this;
return Promise.all([
//Get command
cp.getCommand(constants.HB),
//Find port
cp.findPort()
]).spread((r1, r2) => {
...
After the code review my colleagues suggest to change it to the following which I disagree
since you need to add unnecessary code (the array & push) and Im not sure that this is more readable, what do you think?
run: function () => {
var _this = this;
var promiseArray = [];
//Get command
promiseArray.push(cp.getCommand(constants.HB));
//Find port
promiseArray.push(cp.findPort());
return Promise.all(promiseArray)
.spread((r1, r2) => {

There is no particular reason to put the promises into an explicitly declared array before passing them to Promise.all() so it's pretty hard to defend that the second option is "better" than the first option.
In fact, you could easily make a case that the second option just creates an unnecessary named variable containing the intermediate array and does unnecessary .push() function calls.
In the end, there is no absolute right or wrong here. This is merely a matter of opinion on coding style. Code reviews are often part defensible logic and part reviewer's opinion. It appears you just ran into some opinion where the reviewer has a different opinion than you do.
If you want to push back on a review issue like this, then you should ask them to defend why they their method is necessarily better than your first approach.

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);

To understand monkey patching in Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to understand the concept behind how monkey-patch works in JavaScript?
I've gone through too many examples but couldn't able to understand
For example - Monkey patching the dispatch function in Redux
let next = store.dispatch
store.dispatch = function dispatchAndLog(action) {
console.log('dispatching', action)
let result = next(action)
console.log('next state', store.getState())
return result
}
Source: http://redux.js.org/docs/advanced/Middleware.html#attempt-3-monkeypatching-dispatch
Can anyone please explain monkey patching in simple terms and example
And which is the best scenarios to use it?
Thanks.
Let say you use a library which define a class Test with a method test.
If you want to monkey patching-it you have to use this kind of code and include it after the library :
// replacing current implementation with a new one
Test.prototype.test = function(arg1, arg2, ...){...}
Now let say you want to do something a bit smarter, like adding something to the function without modifying the rest here is how you would do it :
var oldFN = Test.prototype.test;
Test.prototype.test = function([arguments...]){
[...some custom code...]
oldFN.apply(this, arguments);// arguments keyword refer to the list of argument that your function recevied, if you need something else use call.
[...some custom code...]
}
Monkey patching is valid but must be used wisely. Furthermore each time you upgrade the library, you must check that all your patches works still fine.

Local Variable usage reasoning [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 8 years ago.
Improve this question
I have lot enough functions, which look like:
var functionName = function(e) {
//
};
where all the parameters are getting passed in in a single container e. Most times values are simple values (no functions), ex.:
{ parameter1: 1, parameter2: "Name", parameter3:{ subParameter1: "A"}}
But there're times when I pass in functions as in: { p2:function(){...} }
I have two options when it comes to utilising parameter values:
Options 1: get parameter values from the chain, starting from e: e.parameter1, e.parameter3.subParameter1 etc.
Option 2: use cached parameter values:
var parameter1 = e.parameter1;
var subParameter1 = e.parameter3.subParameter1;
The second option improves readability but increases the number of vars and the size of the code base. On another hand it's much drier when using long chains, i.e. e.p1.p2.p3 etc.
What reasoning should I use for choosing between those two options?
**Update 1 - the question sounds quite subjective, let me re-prase it.**
I don't mind using chains all the way, no local vars codebase is smaller, I can always figure out what's what, are the any cases when caching is a must?
A combination, based on depth(e.p1 vs e.p1.sp2.ssp3) and frequency of use. Deeper sub-properties and high usage of any sub-property both benefit from caching.
Nested property look ups can get costly, and caching the value after executing the look up once is valuable if you're going to use it a lot. This is only more efficient if you're accessing a particular property on the chain more than once, and the more you access it, the more you benefit from caching.
If you only have one level deep(e.p1, e.p2, e.p3) and you're only looking up each property value once, don't bother.
If you're accessing e.p1.sp2.ssp3 all throughout your function, cache it for sure.

Categories

Resources