JavaScript Snippet – Convert HTML Table To 2D Array

A few days ago I was working on manipulating data that I found in Wikipedia. The data was in a table where the colspans and rowspans were making it difficult to simply programmatically pull data. Then I started looking into code to turn HTML table to JSON but for some reason the rowspans were still causing issues. Finally, I decided to just write a quick and dirty function to get the job done:

The cool thing about this function is that in the case of cells that span multiple columns and/or rows the value in that cell will be written to each corresponding sub-array value.

JavaScript Snippet – isValidVarName()

Now Available in YourJS

Recently I was working on a function which needed to determine whether or not a string could be used as a variable name. Variable name validation can get tricky so instead of using a crazy regular expression which includes all keywords (which may change over time) and instead of testing for strange unicode characters which are rarely used for variable names, I decided to leverage the JavaScript Function constructor:

The above function takes the string in question and returns true if the string can be used a variable name. If the string can not be used as a variable name false is returned.

Some may wonder why I’m doing the following:

varName.replace(/[\s\xA0,\/]|^$/g, '.')

The reason I included the above replacement is to avoid false-positives in the case of an empty string, extra spacing, commas, and forward slashes.

Security

Others have attempted to make the same function using the evil eval() function which allows for JS injection. Even though the Function constructor can also be used for evil, when supplying arguments it does prevent you from doing JS injection by making sure the arguments don’t have parentheses.

Examples

The following is an example of what will happen when running for the function for a number of strings:

console.log(isValidVarName(''));           // -> false
console.log(isValidVarName('3'));           // -> false
console.log(isValidVarName('3d'));          // -> false
console.log(isValidVarName('D3'));          // -> true
console.log(isValidVarName('D3 '));         // -> false
console.log(isValidVarName('D3,Q'));        // -> false
console.log(isValidVarName('D3/*Qs*/'));   // -> false
console.log(isValidVarName('D3Q'));         // -> true
console.log(isValidVarName('var'));         // -> false
console.log(isValidVarName('true'));        // -> false
console.log(isValidVarName('undefined'));   // -> true
console.log(isValidVarName('null'));        // -> false
console.log(isValidVarName('coolio.pop'));  // -> false
console.log(isValidVarName('coolio'));      // -> true
console.log(isValidVarName('coolio_pop'));  // -> true
console.log(isValidVarName('$'));           // -> true
console.log(isValidVarName('$á'));          // -> true
console.log(isValidVarName('áÑ'));          // -> true
console.log(isValidVarName('_'));           // -> true

Here is a similar example hosted on JSBin:
JS Bin on jsbin.com

JavaScript – Detecting Infinite Loops

When allowing a user to input code that could potentially cause an infinite loop, it is nice to test the code first, right? Even, if the code doesn’t run infinitely, it would be nice to know if it takes longer than you would want. One way to nicely test for infinite loops or long running code is by using web workers. The following is a function which uses eval() in a web worker to execute the code and adds a timeout so that if the code takes too long to run, the web worker will be terminated:

Now let’s say that the user inputs the following loop in your textbox which has an ID of txtCode:

for (var i = 0; i != 10; i++) {
  if (i % 2 == 0) {
    i *= 2;
  }
}

Unfortunately, the above loop will run infinitely because i will progress as shown below:

0
1
4
5
12
13
14
29
30
61
62
125
126
253
254
509
510
1021
...

If you don’t believe me you can try the following code in the console 😉 :

// Let's stop the loop once we get to or above 1000
for (var i = 0; console.log(i + ' != 10'), i != 10 && i < 1000; i++) {
  if (i % 2 == 0) {
    i *= 2;
  }
}

The good thing about web workers is that any code that runs in them will not interfere with your JS in the main process but the downside is that you cant innately determine if a web worker is still running after a specified amount of time (well not as easily as you might hope). Fortunately, with the limitEval() function we find a way around this issue by sending and receiving messages. Feel free to check out how I accomplish this by analyzing the code.

Now let's setup a way to determine if the user's input, found in txtCode, takes more than 3 seconds to run:

var code = document.getElementById('txtCode').value;
limitEval(code, function(success, returnValue) {
  if (success) {
    // do whatever you want with the return value (returnValue)
  }
  else {
    alert('The code takes too long to run.  Is there is an infinite loop?');
  }
}, 3000);

So, if the code takes more than 3 seconds to run an alert will be shown after 3 seconds and the eval will be terminated.

As you can see limitEval takes two required parameters and one optional one:

  1. code {string}:
    The JS code to be eval'd.
  2. fnOnStop {Function}:
    The function which will be called either after the eval completes or after the timeout occurs. The following are the arguments that will be passed:

    1. success {boolean}:
      true will be passed if the eval executed successfully before the timeout. Otherwise false will be passed.
    2. opt_returnValue {*}:
      If the eval executes successfully this will be the return value. If the timeout occurs this will not be passed and arguments.length will be 1.
  3. opt_timeoutInMS {number}:
    Optional. Defaults to 1000. The number of milliseconds before timing out.

It is important to note that this solution, although very useful, only works on newer browsers. According to MDN, it will work in the following browsers and higher:

  • Chrome 23
  • Firefox (Gecko) 21
  • Internet Explorer 11
  • Safari (WebKit) 7

Hopefully you find the limitEval() function useful. Have fun! 😎