How to avoid this case of evil eval? - javascript

I inherited a javascript code base and I am new to javascript. So i am using JSHint to avoid common mistakes, misuses.
JSHint has found this piece of code but i do not know how to avoid the evil eval:
function GetProperties(object) {
var result, property, t;
result = '';
for (property in object) {
if (property.indexOf('Get', 0) === 0) {
t = object[property] + "...";
eval("if (GetNumOfParameter(t) == 0) var m = object." + property + "(); else var m = -100;");
if (window.m != -100) {
result += property + ': ' + window.m + '\r\n';
}
}
}
return result;
}

Use the following, it's far better, you don't need to use m if you don't use it anywhere else.
function GetProperties(object) {
var result, property, t;
result = '';
for (property in object) {
if (property.indexOf('Get', 0) === 0) {
t = object[property] + "...";
if (GetNumOfParameter(t) == 0)
result += property + ': ' + object[property]() + '\r\n';
}
}
return result;
}

Related

how to fix mutable variable is accessible from closure warning with a while loop

Here's my function that is supposed to validate a name so that there is no duplicates:
function validateBucketName(){
var counter = 1;
var validated = false;
var suggestedName = "Bucket " + (vm.buckets.length + counter);
if(vm.buckets.length === 0) return suggestedName;
while(!validated){
var foundIndex = vm.buckets.findIndex(function (bucket) {
return bucket.name === suggestedName;
});
if(foundIndex === -1){
validated = true;
} else {
counter++;
suggestedName = "Bucket " + (vm.buckets.length + counter);
}
}
return suggestedName;
}
I am getting the pretty common error, that I am aware of how to deal with in for loops, but can't figure out how to do that with the while loop. Can someone have a look at this?
Ps. This is probably very inefficient way of trying to make sure no duplicate names exist. If you have a suggestion for how to make that better feel free to comment.
This is a better approach
You don't need the validate variable, just use while(true) because you're going to get the missing suggestedName.
When this condition if (foundIndex === -1) is true return the suggestedName.
Look this code snippet with those modifications:
function validateBucketName() {
var counter = 1;
var suggestedName = "Bucket " + (vm.buckets.length + counter);
if (vm.buckets.length === 0) return suggestedName;
var compare = function(bucket) {
return bucket.name === suggestedName;
};
while (true) {
if (vm.buckets.findIndex(compare) === -1) {
return suggestedName;
else
suggestedName = "Bucket " + (vm.buckets.length + (counter++));
}
return suggestedName;
}

create a span inside a div dynamically in vuex

I'm using an existing web app created using vue.js. and below is the code.
function () {
var e = this,
t = e.$createElement,
n = e._self._c || t;
return e.message.text && "human" === e.message.type ? n("div", {
staticClass: "message-text"
}, [e._v("\n " + e._s(e.message.text) + "\n")]) : e.message.text && e.shouldRenderAsHtml ? n("div", {
staticClass: "message-text",
domProps: {
innerHTML: e._s(e.botMessageAsHtml)
}
}) : e.message.text && "bot" === e.message.type ? n("div", {
staticClass: "message-text"
}, [e._v("\n " + e._s(e.shouldStripTags ? e.stripTagsFromMessage(e.message.text) : e.message.text) + "\n")]) : e._e()
}
and here is my n function
function l(e, t) {
function n(e, t, n, i) {
console.log(typeof e + "\t" + typeof t + "\t" + typeof n + "\t" + typeof i);
return function () {
if (n in t) {
return function () {
if (i && "object" === He()(e[n])) {
return f()({}, l(t[n], e[n], i), l(e[n], t[n], i));
}
return function () {
if ("object" === He()(e[n])) {
return f()({}, e[n], t[n]);
}
return t[n];
}();
}();
}
return e[n];
}();
}
var i = arguments.length > 2 && void 0 !== arguments[2] && arguments[2];
return k()(e).map(function (r) {
var o = n(e, t, r, i);
return Ke()({}, r, o);
}).reduce(function (e, t) {
return f()({}, e, t);
}, {});
}
The above code basically creates a div tag with class name as message-text, I want to create a span inside this div. I am not at all good with vue.js and the code seems pretty confusing. please help me out in creating a span inside this div.
This looks like a compiled code and minified probably. But if you can't get the uncompiled version I would try and simplify the code as it has a spaghetti if else.
function(){
var e = this,
t = e.$createElement,
n = e._self._c || t,
result;
if(e.message.text && "human" === e.message.type){
result = n("div", {staticClass: "message-text"}, [e._v("\n " + e._s(e.message.text) + "\n")])
}else{
if(e.message.text && e.shouldRenderAsHtml){
result = n("div", {staticClass: "message-text",domProps: {innerHTML: e._s(e.botMessageAsHtml)}})
}else{
if(e.message.text && "bot" === e.message.type){
if(e.shouldStripTags){
result = n("div", {staticClass: "message-text"}, [e._v("\n " + e._s(e.stripTagsFromMessage(e.message.text)) + "\n")])
}else{
result = n("div", {staticClass: "message-text"}, [e._v("\n " + e._s(e.message.text) + "\n")])
}
} else {
result = e._e();
}
}
}
return result;
}
You probably need to look into function n which is taking the arguments "div" as string and css class as object "message-text" with other props like innerHTML...

How can I use shorthand if else statement in my js code

I have created the following if else statement but there are so many if else statement. I want to learn how can I make it shorthand?
if(REL == 'Like'){
$('#Like' + dataid).attr('rel', 'NotLike');
} else if(REL == 'Love') {
$('#Love' + dataid).attr('rel', 'NotLove');
} else if(REL == 'Unbelievable'){
$('#Unbelievable' + dataid).attr('rel', 'NotUnbelievable');
} else if(REL == 'Spectacular'){
$('#Spectacular' + dataid).attr('rel', 'NotSpectacular');
} else if(REL == 'Emotional'){
$('#Emotional' + dataid).attr('rel', 'NotEmotional');
}
Just take the variable with a check.
if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(REL) !== -1) {
$('#' + REL + dataid).attr('rel', 'Not' + REL);
}
For a flip-flop based on strings starting with 'Not', you may use this
var temp = REL,
not = 'Not';
if (REL.substring(0, 3) === 'Not') {
temp = REL.substring(3);
not = '';
}
if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(temp) !== -1) {
$('#' + REL + dataid).attr('rel', not + temp);
}
Proposal with state saver
var lastState = '';
function change(state) {
var temp = state,
not = 'Not';
if (state.substring(0, 3) === 'Not') {
temp = state.substring(3);
not = '';
}
if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(temp) !== -1) {
$('#' + temp + dataid).attr('rel', not + temp);
}
return not + temp;
}
// usage always both together:
change(lastState); // to reset the last state
lastState = change(REL); // call change and save the actual state

Looking up an object property within the console. Syntax issue

I'm writing a compare function using objects. I know that if I have the following object - var obj{ one: "foo", two: bar"} and I want to look up a property then obj["one"] will work but obj[one] will not.
However when I do the comparison function it will correctly compare obj["one"] and obj2["one"], but when I'm trying to log it in the console the syntax obj[one] works and obj["one"] comes back as undefined. It doesn't affect the functionality of the code, but I'm confused.
var num = 2;
var num2 = 4;
var num3 = 4;
var num4 = 9;
var num5 = "4";
var obj = {here: {is: "an"}, object: 2};
var obj2 = {here: {is: "an"}, object: 2};
function deepEqual(el, el2) {
var outcome = false;
console.log("comparing " + el + " and " + el2);
if (typeof el == 'object' && typeof el2 == 'object') {
console.log("These are both objects");
if (Object.keys(el).length === Object.keys(el2).length) {
console.log("These objects have the same number of keys");
for (var x in el) {
if (el2.hasOwnProperty(x) && el["x"] === el2["x"]) {
console.log("comparing " + el[x] + " with " + el2[x]);
outcome = true;
} else {
return false;
}
}
} else return false;
} else if (el === el2) {
outcome = true;
}
return outcome;
}
So the part of the code I'm talking about is
if (el2.hasOwnProperty(x) && el["x"] === el2["x"]) {
console.log("comparing " + el[x] + " with " + el2[x]);
outcome = true;
} else {
return false;
}
This comes back correctly in the console as "comparing (property) with (property)". However if I write it like this
if (el2.hasOwnProperty(x) && el["x"] === el2["x"]) {
console.log("comparing " + el["x"] + " with " + el2["x"]);
outcome = true;
} else {
return false;
}
It says "comparing undefined with undefined".
Any insights?
in your code el["x"] does not refer to anything. There is no property in the el object that has an "x" key
you are in a for loop which define x so you need to use that variable instead of "x"
for (var x in el) {
if (el2.hasOwnProperty(x) && el[x] === el2[x]) {
console.log("comparing " + el[x] + " with " + el2[x]);
outcome = true;
} else {
return false;
}
}

Where does this unspecified error comes from?

I'm trying to format any kind of variables to achieve some kind of toString() method.
It's working for pretty complex objects and arrays, handling circular references, but when I try to call it on a jQuery object: format($("body")), for testing it on large complex objects, I got this error:
Unhandled exception at line 330, column 21 in ms-appx://8b94d51c-586e-4f3f-bb9c-fa75d62508cd/js/default.js
0x80004005 - Erreur d’exécution JavaScript: Erreur non spécifiée.
0x80004005 - JavaScript Run-time Error: Unspecified error. // I translated it for you
Here is my code (with a // ERROR! comment next to the line 330):
function format(arg, parents, indent) {
var maxParent = 25;
if (parents === undefined) {
parents = [];
}
if (indent === undefined) {
indent = 1;
}
if (contains(parents, arg)) {
return '<span class="brackets">[Circular]</span>';
}
if (typeof arg === 'string' && parents.length > 0) {
return '"' + htmlEntities(arg) + '"';
} else if (Array.isArray(arg)) {
parents.push(arg);
if (parents.length >= maxParent) {
return '<span class="brackets">[Array]</span>';
}
var ret = "[ ";
for (var i = 0, len = arg.length; i < len; i++) {
if (i !== 0) {
ret += ", ";
}
ret += "<br>";
ret += addIndent(indent);
ret += format(arg[i], parents, indent + 1);
}
ret += "<br>";
ret += addIndent(indent - 1);
ret += " ]";
return ret;
} else if (arg === null) {
return '<span class="void">null</span>';
} else if (arg === void 0) {
return '<span class="void">undefined</span>';
} else if (typeof arg === 'number' && (isNaN(arg) || !isFinite(arg))) {
return '<span class="void">' + arg.toString() + '</span>';
} else if (typeof arg === 'object' && arg !== null) {
if (parents.length >= maxParent) {
return '<span class="brackets">[Object]</span>';
} else {
parents.push(arg);
}
var ret = "{";
var first = true;
for (var key in arg) {
if (!first) {
ret += ", ";
}
else {
first = false;
}
ret += "<br>";
ret += addIndent(indent);
ret += key;
ret += ": ";
if (typeof arg[key] === 'function') {
ret += '<span class="brackets">[Function]</span>';
} else {
ret += format(arg[key], parents, indent + 1); // ERROR!
}
}
ret += "<br>";
ret += addIndent(indent - 1);
ret += "}";
remove(parents, arg);
return ret;
}
return arg;
}
Do you have any ideas why this error is occuring?
What can I do to fix it?
Out of the top of my head I can think that arg[key] is null by the time you call the format function. Synchronize the if statement so it executes only after arg[key] is not null.

Categories

Resources