How to fix the following errors - javascript

I implemented spectrum color picker, and I'm trying to fix up the JSLint errors. I have 2 types of errors which I can't seem to fix. Here are the errors:
Unexpected '~'
Unexpected 'in'. Compare with undefined, or use the hasOwnProperty method instead.
Here's the code for the first error:
function contains(str, substr) {
return !!~('' + str).indexOf(substr);
}
Code for second error:
var hasTouch = ('ontouchstart' in window);

function contains(str, substr) {
return str.indexOf(substr) !== -1;
}
var hasTouch = window.ontouchstart !== undefined;

Related

How to replace arguments.callee to be able to 'use strict' [duplicate]

Is it possible to see the callee/caller of a function when use strict is enabled?
'use strict';
function jamie (){
console.info(arguments.callee.caller.name);
//this will output the below error
//uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
};
function jiminyCricket (){
jamie();
}
jiminyCricket ();
For what it's worth, I agree with the comments above. For whatever problem you're trying to solve, there are usually better solutions.
However, just for illustrative purposes, here's one (very ugly) solution:
'use strict'
function jamie (){
var callerName;
try { throw new Error(); }
catch (e) {
var re = /(\w+)#|at (\w+) \(/g, st = e.stack, m;
re.exec(st), m = re.exec(st);
callerName = m[1] || m[2];
}
console.log(callerName);
};
function jiminyCricket (){
jamie();
}
jiminyCricket(); // jiminyCricket
I've only tested this in Chrome, Firefox, and IE11, so your mileage may vary.
Please note that this should not be used in production. This is an ugly solution, which can be helpful for debugging, but if you need something from the caller, pass it as argument or save it into a accessible variable.
The short version of #p.s.w.g answer(without throwing an error, just instantiating one):
let re = /([^(]+)#|at ([^(]+) \(/g;
let aRegexResult = re.exec(new Error().stack);
sCallerName = aRegexResult[1] || aRegexResult[2];
Full Snippet:
'use strict'
function jamie (){
var sCallerName;
{
let re = /([^(]+)#|at ([^(]+) \(/g;
let aRegexResult = re.exec(new Error().stack);
sCallerName = aRegexResult[1] || aRegexResult[2];
}
console.log(sCallerName);
};
function jiminyCricket(){
jamie();
};
jiminyCricket(); // jiminyCricket
It does not worked for me
Here is what I finally do, just in case it helps someone
function callerName() {
try {
throw new Error();
}
catch (e) {
try {
return e.stack.split('at ')[3].split(' ')[0];
} catch (e) {
return '';
}
}
}
function currentFunction(){
let whoCallMe = callerName();
console.log(whoCallMe);
}
You can get a stack trace using:
console.trace()
but this is likely not useful if you need to do something with the caller.
See https://developer.mozilla.org/en-US/docs/Web/API/Console/trace
functionName() {
return new Error().stack.match(/ at (\S+)/g)[1].get(/ at (.+)/);
}
// Get - extract regex
String.prototype.get = function(pattern, defaultValue = "") {
if(pattern.test(this)) {
var match = this.match(pattern);
return match[1] || match[0];
}
return defaultValue; // if nothing is found, the answer is known, so it's not null
}

Uncaught TypeError: Cannot read property 'toString' of null

I have this message: "Uncaught TypeError: Cannot read property 'toString' of null" while running the code below. Any help would be appreciated since I am not familiar with Javascript
Thank you in advance.
function getUrlVars() {
var arrGamePath = document.referrer;
if(arrGamePath) {
var reg = new RegExp("[/][a-zA-Z]{2}-[a-zA-Z]{2,4}[/]");
var locale = reg.exec(arrGamePath) .toString();
while (locale.indexOf("/") != -1) {
locale = locale.replace("/", "");
}
return locale;
}else{
return false;
}
}
if(getUrlVars()) {
sCID = getUrlVars();
}
Your regex doesn't match and so returns null. null doesn't have a method toString(). So you should check for a match first and if it doesn't match, return false (or do whatever else you want to do - or change your regex so that it matches)
function getUrlVars() {
var arrGamePath = document.referrer;
if(arrGamePath) {
var reg = new RegExp("[/][a-zA-Z]{2}-[a-zA-Z]{2,4}[/]");
var matches = reg.exec(arrGamePath);
if (!matches) return false;
var locale = matches.toString();
while (locale.indexOf("/") != -1) {
locale = locale.replace("/", "");
}
return locale;
}else{
return false;
}
}
if(typeof getUrlVars == 'function') {
sCID = getUrlVars();
}
Also you are calling the function twice, once in your if line, ignoring the result:
if (getUrlVars())
and then if the if returns true, again. Just check if its type is a function instead.
So this error is related to the null property which while you did not declare a null property, that is what you are getting back as #baao shared in the first answer.
So whenever you try to access a property under a value of null or undefined in JavaScript and try to read any property, call any function on it, you get an error message: cannot read properties of null, reading toString(), so that’s what’s going on behind the scenes that’s why you are getting an error.
You are trying to call toString() on matches which is currently null or was null.
In the modern world of TypeScript you could probably solve that like so:
const reg: null || string = new RegExp("[/][a-zA-Z]{2}-[a-zA-Z]{2,4}[/]");
And that might indicate, hey this reg variable is either a string or it might be null.

Javascript/Underscore won't skip undefined result

I am trying to skip a line of code if there is nothing to do. However, I receive the error: TypeError: _.pairs(...)[0] is undefined. Why do I still receive this error? the function conditionalFilter is supposed to skip if it is undefined
Code:
conditionalFilter(_.pairs(_.pairs(_.pairs(d.nodes[0].children)[0][1].children)[0][1].children)[0][1].dimension, d.dimension.name, d.name)
Function:
function conditionalFilter(check, dim, filter){
if (check != "undefined") {
myFunction(check, dim, filter);
} else {}
}
If it makes a difference, the error throws on the line conditionalFilter(_.pairs...)
You need to take the quotes off of undefined,
the way you have it now you are checking it as a string:
function conditionalFilter(check, dim, filter){
if (check != undefined) {
myFunction(check, dim, filter);
} else {}
}

How do you find out the caller function in JavaScript when use strict is enabled?

Is it possible to see the callee/caller of a function when use strict is enabled?
'use strict';
function jamie (){
console.info(arguments.callee.caller.name);
//this will output the below error
//uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
};
function jiminyCricket (){
jamie();
}
jiminyCricket ();
For what it's worth, I agree with the comments above. For whatever problem you're trying to solve, there are usually better solutions.
However, just for illustrative purposes, here's one (very ugly) solution:
'use strict'
function jamie (){
var callerName;
try { throw new Error(); }
catch (e) {
var re = /(\w+)#|at (\w+) \(/g, st = e.stack, m;
re.exec(st), m = re.exec(st);
callerName = m[1] || m[2];
}
console.log(callerName);
};
function jiminyCricket (){
jamie();
}
jiminyCricket(); // jiminyCricket
I've only tested this in Chrome, Firefox, and IE11, so your mileage may vary.
Please note that this should not be used in production. This is an ugly solution, which can be helpful for debugging, but if you need something from the caller, pass it as argument or save it into a accessible variable.
The short version of #p.s.w.g answer(without throwing an error, just instantiating one):
let re = /([^(]+)#|at ([^(]+) \(/g;
let aRegexResult = re.exec(new Error().stack);
sCallerName = aRegexResult[1] || aRegexResult[2];
Full Snippet:
'use strict'
function jamie (){
var sCallerName;
{
let re = /([^(]+)#|at ([^(]+) \(/g;
let aRegexResult = re.exec(new Error().stack);
sCallerName = aRegexResult[1] || aRegexResult[2];
}
console.log(sCallerName);
};
function jiminyCricket(){
jamie();
};
jiminyCricket(); // jiminyCricket
It does not worked for me
Here is what I finally do, just in case it helps someone
function callerName() {
try {
throw new Error();
}
catch (e) {
try {
return e.stack.split('at ')[3].split(' ')[0];
} catch (e) {
return '';
}
}
}
function currentFunction(){
let whoCallMe = callerName();
console.log(whoCallMe);
}
You can get a stack trace using:
console.trace()
but this is likely not useful if you need to do something with the caller.
See https://developer.mozilla.org/en-US/docs/Web/API/Console/trace
functionName() {
return new Error().stack.match(/ at (\S+)/g)[1].get(/ at (.+)/);
}
// Get - extract regex
String.prototype.get = function(pattern, defaultValue = "") {
if(pattern.test(this)) {
var match = this.match(pattern);
return match[1] || match[0];
}
return defaultValue; // if nothing is found, the answer is known, so it's not null
}

Finding undefined variable name string in ReferenceError

My question is simple, but Javascript VM dependent.
When catching a ReferenceError (in my case when doing eval(...)), how do I get back the actual identifier token from the error object?
Matching for "known" error messages and parsing them seems way too hackish for me, but is the only available option to me right now.
edit: For the moment I'm only "matching" V8 and Firefox by doing this:
catch(e){
if (e.name === "ReferenceError"){
var varname = e.toString().replace("ReferenceError: ","")
.replace(" is not defined","").trim();
foobar(varname);
}
}
You should be able to do this using e.message and matching the text up until the first space.
The following code works in IE7/IE8/IE9/IE10/Chrome and Firefox.
try {
alert(tesssst);
} catch(e){
if (e.name === "ReferenceError" || e.name === "TypeError") { //IE7 uses TypeError instead
var variableName = e.message.substr(0, e.message.indexOf(" "));
//IE7 and IE8 fix (it adds ' around the variable name)
if (variableName.substr(0, 1) == "'" && variableName.substr(variableName.length - 1) == "'") {
variableName = variableName.substr(1, variableName.length - 2);
}
console.log(variableName); //tesssst
}
}
Edit:
Added IE7/IE8 fixes
Edit 2:
With a little regex magic you can change this to the following:
try {
alert(tesssst);
} catch(e){
if (e.name === "ReferenceError" || e.name === "TypeError") { //IE7 uses TypeError instead
var variableName = e.message.match(/^'?(.*?)'? /)[1];
console.log(variableName);
}
}

Categories