Typed immutable objects in javascript [closed] - javascript

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

Related

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.

Vuejs 2 + form validation [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 4 years ago.
Improve this question
Since vue-validator https://github.com/vuejs/vue-validator is being ready for Vuejs 2, what is the best way to implement frontend validation?
UPDATE
I've found this awesome plugin
Vee Validate
In my opinion, a good way to implement front end validation for VueJS is to use vuelidate.
It's very simple to use and powerful. It offers model-base validation, it means that it's what you define in data that is validated, so it's totally decoupled from the templates. It comes with common built-in validators for email , min and max length or required. And many others.
Since it's all ultimately Javascript, you could also use some of the existing Javascript validation libraries like Parsely.js or Validate.js to hook this up. One thing that's nice about the Validate.js library is that it's format could easily be stored in the global store if you're using Vuex:
var constraints = {
creditCardNumber: {
presence: true,
format: {
pattern: /^(34|37|4|5[1-5]).*$/,
message: function(value, attribute, validatorOptions, attributes, globalOptions) {
return validate.format("^%{num} is not a valid credit card number", {
num: value
});
}
},
length: function(value, attributes, attributeName, options, constraints) {
if (value) {
// Amex
if ((/^(34|37).*$/).test(value)) return {is: 15};
// Visa, Mastercard
if ((/^(4|5[1-5]).*$/).test(value)) return {is: 16};
}
// Unknown card, don't validate length
return false;
}
},
creditCardZip: function(value, attributes, attributeName, options, constraints) {
if (!(/^(34|37).*$/).test(attributes.creditCardNumber)) return null;
return {
presence: {message: "is required when using AMEX"},
length: {is: 5}
};
}
};
Then used as such:
validate({creditCardNumber: "4"}, constraints);
// => {"creditCardNumber": ["Credit card number is the wrong length (should be 16 characters)"]}
validate({creditCardNumber: "9999999999999999"}, constraints);
// => {"creditCardNumber": ["9999999999999999 is not a valid credit card number"]}
validate({creditCardNumber: "4242424242424242"}, constraints);
// => undefined
validate({creditCardNumber: "340000000000000"}, constraints);
// => {"creditCardZip": ["Credit card zip is required when using AMEX"]}
You could also hook those validate() functions to your component with something along the lines of #blur=validate(...)
Currently there are not many choices. Take a look at vue-awesome where you can find the most relevant libraries. There are 2 at the moment.
If you are using semantic-ui or its an option for you they have an amazing form validation plugin.
semantic-ui-form-validation
I've used it with Vuejs and it works great.
I found this validator simple, flexible and well documented. It cover most scenarios of validating forms in Vue Js.
I used Jquery validator plugin in the past. Compared to that, this simple-vue-validator really stands out in its flexibility and its ability to validate both hard-coded and dynamically generated forms.
https://github.com/semisleep/simple-vue-validator
I used it extensively for my SaaS project and so far it has gone on really well.

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

Why immutable does not complain on attempt to change value [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'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.

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;

Categories

Resources