Category Archives: JavaScript

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 :wink: :

// 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! :cool:

JavaScript Snippet – Recurse A Directory Synchronously

Recently I took a look at making HTML5 programs that will work on Mac, Linux and Windows via Electron and needed a way to recurse a directory synchronously in Node.js. I ended up with the following code:

The above function allows us to recursively get the contents of a directory. It also provides the ability to filter out files and sub-directories. The following is an example of using it to simply get all files and directories within a specified directory:

var dir = recurseDirSync('/Users/jsmith/Movies');

/*****
// Example directory structure:
{
  isFile: false,
  path: '/Users/jsmith/Movies/',
  stat: ,
  files: [
    {
      isFile: true,
      path: '/Users/jsmith/Movies/Scrooge McDuck.mp4',
      stat: ,
    },
    {
      isFile: false,
      path: '/Users/jsmith/Movies/The Other Movies/',
      stat: ,
      files: [...]
    },
    ...
  ]
}
*****/

As you can see, get the files and sub-directories of a directory is very easy. You can also easily filter with this function. Let’s say we want to only include directories and MP4s:

recurseDirSync('/Users/jsmith/Movies', function(path, isFile, stat) {
  return !isFile || /\.mp4$/i.test(path);
});

Once again, using this helper function makes something that could’ve been complex a lot easier. Feel free to use and even modify this function. :cool:

Game – Bible Book Master

Yesterday I really wanted to make a multi-lingual so I decided to make a game in which you have to go through all of the books of the Bible as fast as you can. I still need to do some work on the game to make it more user-friendly, but the following (which can also be accessed here) is what I came up with:

As of when I wrote this post the game supported 9 languages including English, Spanish, Vietnamese, Korean, and Haitian Creole. I chose the languages based on those in which I could find the names of all 66 Bible books. In fact, in all cases except for Vietnamese I used the Online Watchtower Library on jw.org in order to get the bible book names, using this JavaScript code in the web console:

$('.book .name').map(function() {
  return $(this).text();
});

As far as translating the rest of the words in the game, since I kept the amount of text to a minimum I simply used good ol’ Google Translate.

Since I wrote the server-side in PHP I ended up using $_SERVER['HTTP_ACCEPT_LANGUAGE'] to auto-detect the language if it wasn’t set:

$lang_code = valueOf($_REQUEST['lang'], preg_replace("/\W.*/", "", $_SERVER['HTTP_ACCEPT_LANGUAGE']));

Finally, I spent way more time than I wanted to on the rounded CSS3 buttons:

.round-button {
  font-size: 64px;
  line-height: 3em;
  height: 3em;
  width: 3em;
  border-radius: 3em;
  background: #000;
  color: #FFF;
  display: inline-block;
  text-align: center;
  font-family: fontello;
  transition: 0.5s cubic-bezier(0.5,0.5,0.5,0.5) all;
  cursor: pointer;
  box-shadow: 0 0 0.25em #000;
  z-index: 1;
  position: relative;
  border: 0.05em solid #000;
  padding: 0.45em;
  margin: 0.5em;
  box-shadow: 0 0 1em 0.5em rgba(0,0,0,0.5) inset, 0 0 0 #000;

  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
}
.round-button .text {
  font-size: 0;
  position: absolute;
  line-height: 1em;
  margin-top: -2em;
  display: block;
  width: 6em;
  text-align: center;
  text-shadow: 0 0 3px #FFF, 0 0 3px #FFF, 0 0 3px #FFF, 0 0 3px #FFF, 0 0 3px #FFF;
  transition: 0.5s ease all;
}
.round-button:hover {
  box-shadow: 0 0 0 0 #000 inset, 0 0 0.125em 0.125em #FFF, 0 0 0.0625em 0.25em rgba(0,0,0,0.5);
  background: #FFF!important;
  z-index: 2;
  transform: rotate(360deg);
  -webkit-transform: rotate(360deg);
  color: #000;
  padding: 0;
  border-width: 0.5em;
}
.round-button:hover .text {
  font-size: 0.5em;
  text-shadow: 0 0 3px #FFF, 0 0 3px #FFF, 0 0 3px #FFF, 0 0 3px #FFF, 0 0 3px #FFF;
}
.round-button:active {
  box-shadow: 0 0 1em 0.1em #777 inset, 0 0 0.125em 0.125em #FFF, 0 0 0.0625em 0.25em rgba(0,0,0,0.5);
  transition: 0.1s ease box-shadow;
}

As you will see in the game, each rounded button is actually individually colored. For example, the following is for the facebook button:

.round-button.facebook {
  background: #3b5998;
  border-color: #3b5998;
}
.round-button.facebook:hover {
  color: #3b5998;
}

All-in-all I am happy with how this game turned out but I would like to add a few improvements. Try the Bible Book Master game out yourself and let me know what you think. :cool:

Game – Where’s the Nose that Knows?

I noticed that lately there has been interest in finding a panda in a large array of snowmen in this post. There was also this post where you have to find a cat amidst a great deal of owls. I started thinking about how I could make a similar game that is randomly generated. I ended up with the following HTML5 version in which you have to either find the one face with a nose or the one face without a nose:

Here is a link to the actual page. Let me know what you think! :cool:

YourJS – 1st Pass

I finally have the 1st pass of YourJS available to the public!!!

What is YourJS?

YourJS is a fully customizable JavaScript library which gives the developer more control than ever before.

Who controls the codebase?

Everyone does! All you have to do is sign up and you can start writing code that can be included in YourJS.

How do I design and download my own library?

As of right now there is a section called Snippets which is a repo of code that can be included in your custom JS library. You can browse the snippets, add the ones you like to the build and then go to the build page to build the library from the selected snippets. Finally, you will have the opportunity to name your library (this will be the variable name added to the global namespace for your utility library).

What development plans are there?

  • Port most functionality available in jPaq over to YourJS.
  • Add an examples section similar to the one that exists on jPaq.org.
  • Include a buildable version of the library which includes documentation.
  • A link share for all other JS sites.

I have a lot of ideas for YourJS so the sky is the limit! Let me know if you have any suggestions and perhaps I will be able to include them in the next iteration of changes. :cool:

YouTube Thumbnail Images

Did you know that YouTube automatically generates thumbnail images for all videos? Each video gets the following four thumbnail images automatically generated:

  • http://img.youtube.com/vi/{VIDEO_CODE}/default.jpg
  • http://img.youtube.com/vi/{VIDEO_CODE}/1.jpg
  • http://img.youtube.com/vi/{VIDEO_CODE}/2.jpg
  • http://img.youtube.com/vi/{VIDEO_CODE}/3.jpg

In addition to these thumbnail images, a larger still of the video is generated and stored in http://img.youtube.com/vi/{VIDEO_CODE}/0.jpg.

Try Me!

I wrote the following JSBin example to display the thumbnails for the specified YouTube video URL:
JS Bin on jsbin.com

If you worked at Monetate in the year 2012 I am sure you recognized the Harlem Shake video :-D. Anyway, you can find a lot more information in the YouTube Data API. This post is just a quick example showing how easy it is to get the thumbnail images for a specific video. Have fun! :cool:

JavaScript Snippet – getClass()

If you have been using JavaScript for a little bit you probably already know how to determine a variable’s class constructor, but just in case you are overthinking it here is a hint: variable.constructor. :-) Of course, many times I like to make functions that will spit my results for me so here is one that will take any variable and spit out its class constructor:

OK, yeah I know that JavaScript doesn’t really have classes but prototypes but most people think of them as classes so that is why this is called getClass(). The one thing you will notice is that if null or undefined is passed into the function, the same value will be passed back since those are the only two things in JavaScript that don’t have corresponding prototypes. Have fun! :cool:

JavaScript – Getting Function Parameter Names

Two years ago I wrote a post about how to pass arguments by name in JavaScript. Recently I have started to ramp a new project call YourJS and found a need to be able to read the names of the parameters of the given function. The following getParamNames() function takes an arbitrary function and returns an array of its parameter names:

Using this function is quite simple. Let’s say that getParamNames() and the function below are defined:

function repeat(string, times, opt_delimiter) {
  opt_delimiter = arguments.length > 2 ? opt_delimiter + '' : '';
  return new Array(times + 1).join(opt_delimiter + string).replace(opt_delimiter, '');
}

Running getParamNames(repeat) will result in the following:

>>> getParamNames(repeat)
["string", "times", "opt_delimiter"]

Running getParamNames(getParamNames) will result in the following:

>>> getParamNames(getParamNames)
["fn"]

Pretty cool, right?!?! Have fun! :cool:

JavaScript Snippet – Using Degrees with Cosine, Sine & Tangent

Now Available in YourJS

Yesterday I was working with Math.cos, Math.sin and Math.tan and was thinking it would be nice to have the equivalent functions which accept the values in degrees instead of radians. For that reason I wrote the following definitions for Math.cosd, Math.sind and Math.tand:

After executing the above 5 lines you will be able to get the cosine at 45° by doing Math.cosd(45) or the sine at 75° by doing Math.sind(75) or the tangent at 135° by doing Math.tand(135). WARNING: this does extend a built-in object. If you would like these functions in a separate Degrees object so as to avoid mutating a built-in object you could use this:

(function (R) {
  Degrees = {
    cosd: function(d) { return Math.cos(d * R); },
    sind: function(d) { return Math.sin(d * R); },
    tand: function(d) { return Math.tan(d * R); }
  };
})(Math.PI / 180);

Have fun! :cool: