Why immutable does not complain on attempt to change value [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
I'm looking through the documentation for Immutable library and was quite surprised by the fact that attempt to change a value on immutable collection just ignoring the action and does not throw an exception.
This is example from the documentation
import Immutable = require('immutable');
var map1: Immutable.Map<string, number>;
map1 = Immutable.Map({a:1, b:2, c:3});
var map2 = map1.set('b', 50);
map1.get('b'); // 2
map2.get('b'); // 50
Why is it implemented in this way, wouldn't be better to throw an exception and therefore expose the error in the code?
UPDATE
I'm more java developer and I instinctively assume that behavior of immutable collections in JS will be similar to Java. Java's immutable collections will throw UnsupportedOperationException on the attempt to modify the collection.
I appreciate that javascript is a different language and it can have its own rules and view on how it should behave. I'm not saying that it is wrong I just want to understand the motivation behind the decision to allow calls to set/push etc methods on immutable collection.

Notice how it returned a new object, though:
var map2 = map1.set('b', 50);
map1.get('b'); // 2
map2.get('b'); // 50
map1.get('b'); // 2 <--- It's still 2!
I do agree to a certain extend that maybe this shouldn't be allowed, but its handy to have it function like that, sometimes you want a new object with a key modified. At any rate, it would failing its job if this happened:
map1 = Immutable.Map({a:1, b:2, c:3});
map1.get('b'); // 2
var map2 = map1.set('b', 50);
map1.get('b'); // 50 <--- Oh, no!!!
I hope that helps.

I think you were looking for frozen objects, but instead happened on immutable because it's a namesake with the immutable collections in Java. The immutable js serves a very different purpose aside from providing immutable encapsulation around native mutable types. It allows easy :p and rich structure modifications too. Hence this behavior. I think if all you are interested in is to have a frozen object which doesn't allow for any modifications, please take a look at Object.freeze.

Related

JSON structure 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 days ago.
Improve this question
I am trying to create a javascript structure that looks like that:
[{'red': {color:'red},...}]
starting with an array of colors:
const COLORS = ['red','yellow']
This is what I have tried:
const finalArray = COLORS.map(color => ({ [color]: { color } }))
However this produces an array that looks like that:
[{red: {color:'red'}}]
instead of [{'red': {color:'red'}}]
Which is not the same and will prevent the library I am using from understanding the array.
Any idea is welcome.
I edited the question since there where some typos. Hope it’s clearer now.
Thanks
What are the differences between:
[{red: {color:'red'}}]
// and
[{'red': {color:'red'}}]
If it's only a quote related matters, you can do like:
COLORS.map(color => ({ [`'${color}'`]: { color } }));
These are just two ways of representing the same array/object. If you need a string containing the canonical representation of the array/object (with double quotes around the names of the properties), you can use JSON.stringify(finalArray).
Please note this will quote ALL your property names, like in:
[{"red":{"color":"red"}}]
And please note the above is a string, as if you did:
finalString = '[{"red":{"color":"red"}}]'
(Note: this question has been closed, and I agree it's not clear enough. But it's quite evident that the user is confusing the internal structure of an array/object with its external representation, and with the way the array/object is shown by a development environment, browser, etc. As this is a very common problem, mostly in new programmers or newcomers to a tool, the question and the answers may still be helpful.)

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.

Give a second name to a variable in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I have a code source that contains a long variable name (postCustomThumbnailsScrollerHeight).
I don't want to rename this variable for the whole code source so that I easily continue the project, but to have a shorthand of its name. I tried following solution (which works) at the first declaration of the variable, but I am not sure if it is the correct way to do so. I have a different color of d in IDE:
var postCustomThumbnailsScrollerHeight= d= $('.post-scroller').outerHeight();
I am seeking by this question your usual expert advice.
No, this isn't really correct: you're not declaring the d variable, only assigning to it, and thus
making it global (which may or not be desired)
making your code incompatible with strict mode
Here's a solution:
var d = $('.post-scroller').outerHeight(),
postCustomThumbnailsScrollerHeight = d;
Note that this should only be done for readability/typing issues, not for downloaded script size: minifiers should be used for that latter goal.
Be also careful that you're not making an alias, but really two variables. If you assign to one, you won't change the other one. It's hard to give a definite advice without more information but the usual solution is to have namespaced object:
Assuming you have a struct
myApp.thumbnailScrollers.postCustom = {height:...
then you would just assign that latter object to a local variable in a module or function:
var s = myApp.thumbnailScrollers.postCustom
In this case, changing s.height would also change myApp.thumbnailScrollers.postCustom.height.
Probably you have different color because in this case b it's global variable.
As for my opinion will be better to write all definitions on different lines:
var postCustomThumbnailsScrollerHeight = $('.post-scroller').outerHeight();
var d = postCustomThumbnailsScrollerHeight;
Although JavaScript doesn't natively support references, you can stimulate them using code such as this:
function d(){
return postCustomThumbnailsScrollerHeight;
}
Then just use d() everywhere. It's not very elegant, but as far as I know it's the only way to get a reference in JavaScript.
Do you have a problem declaring that var in the next line?
You could just do:
var postCustomThumbnailsScrollerHeight = $('.post-scroller').outerHeight();
var d = postCustomThumbnailsScrollerHeight;

Typed immutable objects in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I am trying organize data types in React Flux-like application. All my data objects are immutable, for collections I am using immutable.js, which is perfect library for that. But for typed objects i use my own classes. I don't think it is the best solution, but i need to somehow handle default values, internal consistency, validations of data, add methods to that objects etc.
Is there some library available for that purpose?
Do you use immutable.js collections also for that kind of objects? So you handle consistency of data, validations and other functionality somewhere else?
Or do you use plain classes for that?
Do you think that is good idea to have typed objects in React/Flux based application?
Here is example of what kind of objects i mean and simple example how I use it.
class Event extends MyImmutableLib {
constructor(plain) {
this.start = plain.start;
this.end = plain.end;
this.name = plain.name || "unnamed event"; // some default value
this.attendants = plain.attendants || [];
this.valid = plain.start < plain.end; // simple check of validity, I can also throw exception if it is needed
Object.freeze(this); // I use freeze to be sure I don't accidentally change the object
}
getDuration() {
return this.end - plain.start; // methods are sometimes useful
}
addAttendant(newPerson) {
return this.set("attendants", this.attendants.concat([newPerson])) //immutable edit, so I return new object
}
}
var someEvent = new Event({start: new Date("2015-02-29"), end: new Date("2012-02-30")}) //
var jsMeetup = someEvent.set("name", "9th Js Meetup, Brno")
var jsMeetup = jsMeetup.addAttendant("Joe");
console.log(jsMeetup.name, jsMeetup.getDuration())
The best would be some library with:
Typed objects - so I would have my data better organized.
Default values
Validations
Methods
Immutability specific functions

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