Tag Archives: YourJS

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

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:

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:

JavaScript – Number.getOrdinalFor()

Now Available in YourJS

When dealing with numbers, at times for presentation’s sake, we need to add ordinals to numbers. For example, instead of today is the “September 28″, you may want to say that it is the “28th of September”. I wrote the following code snippet to easily add the ordinal for any integer in JavaScript:

(function(o) {
  Number.getOrdinalFor = function(intNum, includeNumber) {
    return (includeNumber ? intNum : "")
      + (o[((intNum = Math.abs(intNum % 100)) - 20) % 10] || o[intNum] || "th");
  };
})([,"st","nd","rd"]);

Description

Gets the appropriate ordinal (“st”, “nd”, “rd”, or “th”) for the specified integer.

Parameters

  1. intNum:
    The number for which the ordinal will be produced.
  2. includeNumber:
    The value that is evaluated as a boolean to determine whether or not to include the specified integer in the returned string. This is optional and thusly defaults to false.

Returns

The string containing the ordinal for the specified integer. If the second parameter evaluates to true, the specified number will returned with the ordinal appended to it.

Examples

The following shows how you could call this function:

var num1 = 1,
    num2 = 12,
    num3 = 123,
    num4 = 1432;
var str1 = Number.getOrdinalFor(num1, true), // 1st
    str2 = Number.getOrdinalFor(num2, true), // 12th
    str3 = Number.getOrdinalFor(num3, true), // 123rd
    str4 = Number.getOrdinalFor(num4, true); // 1432nd

You could even get a little fancy and run this on all of the numbers in a string by doing something like the following:

var str = "1, 2, and 3 place will get medals while 4 and later will get Cinnabons.";
alert(str.replace(/(\d+)/g, Number.getOrdinalFor));

The reason the above example works is because the first parameter that is passed into the function is the entire match, which in this case is the number found. The second parameter passed is the exact same thing, which since it is a string of one or more characters, will always evaluate to true. Having these two circumstances in mind, in every case that a number is found, the same number with the appropriate ordinal is replaces the number in the string.

You could modify it a bit to make it work with any numbers by doing something like this:

var str = "1, 2, 3, 4.5, 6, and 7.8 are all numbers.";
alert(str.replace(/\d*\.\d+|(\d+)/g, function(match, int) {
  return int
    ? Number.getOrdinalFor(parseInt(int, 10), 1)
    : match;
}));

I will not go into detail and explain why the above works. If you don’t understand it, I suggest, if you want to become really proficient in the language, that you dissect the code. Many times, if we try things out ourselves, we will be more likely to remember and understand why something works and when we can use something like that again. Of course, if you do get to a point where you just don’t understand something, leave a comment below and I will help you out. Have fun!!!

JavaScript – String.prototype.replaceAll()

Now Available in YourJS

For those of you who don’t know too much about regular expressions or just want to be able to replace every occurrence of a substring with something else, perhaps this definition for the replaceAll() function of all instances of String object will prove beneficial:

String.prototype.replaceAll = function(target, replacement) {
  return this.split(target).join(replacement);
};

Yep, that’s it! No more code is necessary in order to make the following work as expected:

// Display:  Chriz Wezt
alert("Chris West".replaceAll("s", "z"));

// Display:  Peter Piker kicks kekkers.
alert("Peter Piper picks peppers.".replaceAll("p", "k"));

// Display:  Anteedeesestableeshmentareeaneesm
alert("Antidisestablishmentarianism".replaceAll("i", "ee"));

By default, this function also works with regular expressions. Regardless of the global flag being set for a regular expression, this function will replace each match that is found.