To understand monkey patching in Javascript [closed] - javascript

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.

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

Promise all convention approaches [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
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.

Using String/Array String as Variable name 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 8 years ago.
Improve this question
I'm coding a game with CraftyJS which uses JavaScript and I ran into problem where I have for loop and I need to use Variable name based on Array String... I have been trying to make it work for few hours now so I'm too tired to explain but please help me if anyone hear this!
So basicly what I'm trying to do is this:
var "TempVar"+Array[i] = Something;
also tried it whitout quotes etc... And by passing it in normal String and then using that but I didn't get it working either. If anyone know how this is supposed to do in JavaScript, or if there is alternative method please let me know that.
Sorry about my bad English, its terribly late and English is not my native language.
Also notice that I'm new to JavaScript so don't hate me too hard...
Basically youre going to need to do this:
//Create an empty object
var myObject = {};
for(var i=0; i<Array.length;i++)
{
//Add properties to the object
myObject["TempVar"+Array[i]] = Something;
}
Create an empty object and then append new properties to it within your loop. JavaScript has this neat little way properties are accessed. You can either use a dot notation like so:
myObject.property = "Blah";
Or you could access the property like an array:
myObject["property"] = "Blah";
Both perform the same operation.

Categories

Resources