Refactoring JScript code - javascript

How can I make this code into a one line instruction?
var qe : QuestionnaireElement = state.Parameters["demobreak"];
var qid : String = qe.QuestionId;
qid != "q45"
public class QuestionnaireElement : ParameterValue, IParameterValue, ICloneabl
My real question is:
How can I cast in JScript objects?
((QuestionnaireElement)state.Parameters["demobreak"]).QuestionId != "q45"

I can't test this, but wouldn't
(state.Parameters["demobreak"]:QuestionnaireElement).QuestionId != "q45"
do it?

Sorry for all of you if I make waste your time. I was kind of desesperate to find out the solution, and like always, once that seen the solution, everything looks easier.
The final answer is (or at least a solution is):
(QuestionnaireElement)(state.Parameters["demobreak"]).ValueId != report.DataSource.GetProject("ds0").CreateQuestionnaireElement("q45").ValueId

Related

assign result of comparison to variable javascript

If I do that:
var importance_not_matched = {{item.this_article_importance}} <= article_importance;
It seems to work but in my IDE (Pycharm) I have errors:
"Expression expected" on the "<="
and
"underterminated statment" on the final ";"
I'm using flask, item.this_article_importance is an int
I solved my issue by changing to:
year_not_matched = {{item.this_article_year <= article_year}};
I don't understand why it's better yet though
Depending on the type of value that is {{ item.this_article_importance }} you may have to use filter |safe, so that django does not escape it.
Something like this:
var importance_not_matched = {{ item.this_article_importance|safe }} <= article_importance;
You can verify that both variables really have the desired value, even the type, to ensure where the error comes from.
var this_article_importance = {{ item.this_article_importance|safe }};
console.log(typeof(this_article_importance), this_article_importance);
It's hard to know more without more information. You can review this question where the topic is discussed.
I solved my issue by changing to:
year_not_matched = {{item.this_article_year <= article_year}};
I don't understand why it's better yet though

shorten javascript code - check if property exists and is not empty [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 6 years ago.
Is it possible to shorten this code?
var access_followup = user_access && user_access.followup && user_access.followup.access ? true : false;
Unfortunately JS does not have a null conditional operator. You could write helper function for it or use a slightly less effective method of creating dummy objects:
var access_followup = !!((user_access || {}).followup || {}).access;
which is shorter and prevents using the property names more than once, but doesn't improve readability. The !! is used to enforce a boolean value even when the values don't exist
Maybe I am answering the wrong thing, but why would you want to make it shorter? I'd vote to make it a bit longer, but easier to read for people who work with your code ( including you :) ).
You could make it more readable by splitting it up into multiple lines:
var access_followup = (
user_access &&
user_access.followup &&
user_access.followup.access === true // if access is a boolean value
);
Or, in case you really really want to have short code and you do not use a minifier already, you can try https://jscompress.com/ (which actually compresses any code you paste into it! but makes it WAY less readable).
If the first 2 checks are because you are protecting against exception thrown when user_access.followup is undefined, you can try this:
var accessFollowup;
try {
accessFollowup = !!user_access.followup.access;
} catch (e) {
accessFollowup = false;
}
You could also shorten by removing just the ternary by using !! to force last element into Boolean value:
var access_followup = !!user_access && !!user_access.followup && !!user_access.followup.access
very ugly code that works
var access_followup = (followup = (user_access || {}).followup) && followup.access;

JavaScript: shorthand for conditionally adding something to an array

I am writing a Mocha test for a server at work.
I get two potential phone numbers for a customer, at least one of which will be defined.
var homePhone = result.homePhone;
var altPhone = result.altPhone;
I want to use underscore's _.sample function to pick one of these at random. However, one of them may be undefined.
So what I was thinking was something like:
//pseudocode
var phone = _.sample([homephone || (doNothing), altphone || (doNothing)]);
the _.sample function looks like this:
http://underscorejs.org/#sample
the problem of course, is there is no shorthand syntax that I know of to conditionally add something to an array.
The verbose way to do what I want is:
var phoneArray = [];
if(homePhone){
phoneArray.push(homePhone);
}
if(altPhone){
phoneArray.push(homePhone);
}
var phoneSelection = _.sample(phoneArray);
is there a more elegant way to do this in JavaScript?
You could use .filter:
_.sample([homephone, altphone].filter(_.identity))
Another way would be:
_.sample([homephone, altphone]) || homephone || altphone;
Since you're already using underscore, I would suggest leveraging compact:
var phone = _.sample(_.compact([homephone, altphone]));
This is basically a shortened version of dave's answer, since compact is literally implemented as function(array) { return _.filter(array, _.identity); }.
What about:
var phone = (homephone && altphone)? _.sample([homephone, altphone]) : (homephone || altphone);
Array literals in JavaScript:
[ 1, 2, 3 ]
...are a way to statically declare which things go in which positions in an array. In other words, when you write the code, you already know where things will go.
In your scenario, the positions are only known dynamically. In other words, you don't know where they'll go until you run the program on a given set of inputs.
So basically what you're asking for is impossible, barring any radical changes to how array literals work in future versions of JS. However, if all you want is to save typing, #dave's answer is pretty nice. I'm mainly just clarifying that array literals by themselves don't have this capability.

Meteor Leaderboard Example JS Pattern Explanation

In the Meteor Leaderboard example, there is the following line of Javascript code:
Session.equals("selectedPlayer", this._id) ? "selected" : '';
I know this is shorthand JavaScript, I believe for some sort of 'if' statement, but I can't remember exactly how it works. I was wondering if someone could provide an explanation of what exactly is going on here. Many thanks!
var x = conditionExpression ? trueExpression : falseExpression
// The above is equivalent to the one below.
if(conditionExpression){
var x = trueExpression
}else{
var x = falseExpression
}

Is it safe to run code inside the conditional operator?

I often see and use codes like:
var myvar = (1 < 2) ? 3 : 4 ; //if 1 < 2 then myvar = 3, else = 4
But I just recently saw a code that was executing code, just like some kind of replacement for the if(){}else{}:
Example:
(1 < 2) ? alert("example1") : alert("example2");
The first thoughts that came to me were, "wow, this is like 6-7 characters shorter", "endless of possibilities" or "this made my day".
My question:
Is this thing error-free and safe to use? (like, with a lot of code inside, and nested stuff)
For now, I will just keep using it in the normal way, I have the fear that if I start using it to execute pieces of code might not work.
Is this thing error-free and safe to use? (like, with a lot of code
inside, and nested stuff)
Yes. However, the more code that's within it, the less readable it becomes.
I prefer to use it (the conditional operator) for short, concise statements. Anything more complex deserves an if/else for the sake of readability and maintainability.
There are some exceptions. You can't do this with:
break
continue
Any block like if, for, while, do, or try
for example. What's more, it can mess with your order of operations:
x < 3 ? l = true : r = true; // Syntax error, = has lower precedence than ?:
But that's not the reason not to do it, it's because it's ugly. Which one is clearer to you, this:
if(i > 5) {
alert('One');
} else {
alert('Two');
}
or
i > 5 ? alert('One') : alert('Two');
? It's not quite right, is it? And saving characters is never a reason to do anything, really; otherwise there would be no comments or whitespace. A good minifier like Google Closure Compiler will automatically convert these for you when possible, and there are plenty of other places to save. In the end, it's just whatever you find most convenient and readable.
Also, if you do end up needing break, continue, etc. then it's going to be rather inconsistent and unattractive code.
You're referring to the ternary operator. It's usually used for setting variables with simple strings like this:
var phone = old ? "blackberry" : "iPhone"
That much simpler than using an if:
var phone = "iphone"
if (old) {
phone = "blackberry"
}
It's good in this context, in the example you described and as soon as it starts getting confusing or I'd definitely not recommend it!
Your example might be made better like this:
var msg = 1 < 2 ? "alert1" : "alert2";
alert(msg);
You could also write:
alert( 1<2? "example1" : "example2" );
The ternary opertator is designed for simple cases, sometimes developers get carried away and use it to replace multiple if..else statements, e.g.
var someVal = foo < bar? 'yes' : bar > fum? : fum : fi != fee? fi : fee;
which is not a good idea IMHO.

Categories

Resources