Category archive - Code

A few handy Javascript Methods

So I’ve been doing a LOT of Javascript programming in the last few days and I ran into a few limitations of the language or constructs within the language. For example, certain versions of IE do not support the Array.indexOf() method. Another problem I ran into is that the Javascript language does not contain a method for performing deep copies on objects. So after some Googling I found a few ways around the aforementioned problems. The first one (indexOf) is as follows:

Array.prototype.findObject = (
!Array.indexOf ? function (o) {
var l = this.length + 1;
while (l–) {
if (this[l - 1] === o) return l – 1;
}
return -1;
} : function (o) { return (this.indexOf(o) !== -1); }
);

The above code will add the ‘findObject’ method to your Array objects. Then you can use that instead of indexOf() and be guaranteed that it will work regardless if the browser supports indexOf or not.

The second one (deep copying) can be circumvented by creating a helper method which will perform the copy for you:

var ObjectHandler = {
//public method
getCloneOfObject: function(oldObject) {
var tempClone = {};

if (typeof(oldObject) == “object”)
for (prop in oldObject)
// for array use private method getCloneOfArray
if ((typeof(oldObject[prop]) == “object”) &&
(oldObject[prop]).__isArray)
tempClone[prop] = this.getCloneOfArray(oldObject[prop]);
// for object make recursive call to getCloneOfObject
else if (typeof(oldObject[prop]) == “object”)
tempClone[prop] = this.getCloneOfObject(oldObject[prop]);
// normal (non-object type) members
else
tempClone[prop] = oldObject[prop];

return tempClone;
},

//private method (to copy array of objects) – getCloneOfObject will use this internally
getCloneOfArray: function(oldArray) {
var tempClone = [];

for (var arrIndex = 0; arrIndex <= oldArray.length; arrIndex++)
if (typeof(oldArray[arrIndex]) == “object”)
tempClone.push(this.getCloneOfObject(oldArray[arrIndex]));
else
tempClone.push(oldArray[arrIndex]);

return tempClone;
}
};

Just thought I’d share those with everyone. Credit for the majority of the deep copy code goes to http://blog.pramatiservices.com/deep-copy-in-javascript/ and credit for the findObject code goes to someone other than me, but I didn’t bookmark the link so I can’t find it again. Sorry :(

FIX: When you undock some windows or change the window layout in the Visual Studio 2008 Service Pack 1 IDE, the IDE crashes

FIX: When you undock some windows or change the window layout in the Visual Studio 2008 Service Pack 1 IDE, the IDE crashes.

I just thought I re-post this incase anybody stumbled upon my blog before they landed on the Microsoft page that had the fix for IDE crashes. I experienced this only one time when I was moving/undocking windows.

Enjoy.

Helpful Extension Methods to the System.String Class in C#

I’ve been doing a decent amount of string manipulation lately and decided to combine that with my newfound knowledge about .NET extension methods. If you don’t know what extension methods are, they’re basically a way to extend a class without needing the source code to that particular class–hence why I can extend the System.String type by simply writing another class. The key is with the parameters of your methods. Here’s the basic gist of it:

public static {Your Return Type} {Your Method Name} ( this {Type/Class you want to extend} {Parameter Name} )
{
     /* Your method body */
}

 

So the key here is the “this” keyword before the type identifier in the parameter list of the method.

I’ve wrapped all of my extension methods into a single class simply called “ExtensionMethods” and added it to my project. The namespace doesn’t matter, so I haven’t included it in this example. You can either use the global namespace (though I don’t recommend it) or just create your own namespace called whatever you want.

Without further adue, here’s the code:

public static class ExtensionMethods
{
    /// <summary>
    /// Includes the trailing path delimiter.
    /// </summary>
    /// <param name="InputPath">The input path.</param>
    /// <returns>The input path including a trailing path delimiter if it doesn't have one</returns>
    public static string IncludeTrailingPathDelimiter(this string InputPath)
    {
        if (!InputPath.EndsWith(Path.DirectorySeparatorChar.ToString()) &&
            !InputPath.EndsWith(Path.AltDirectorySeparatorChar.ToString()))
            return InputPath + Path.DirectorySeparatorChar;
        return InputPath;
    }

    /// <summary>
    /// Asserts the trailing path delimiter.
    /// </summary>
    /// <param name="InputPath">The input path.</param>
    public static void AssertTrailingPathDelimiter(this string InputPath)
    {
        InputPath = InputPath.IncludeTrailingPathDelimiter();
    }

    /// <summary>
    /// Trims the extension from a file name.
    /// </summary>
    /// <param name="InputFile">The input file.</param>
    public static void TrimExtension(this string InputFile)
    {
        int start, count;
        if ((start = InputFile.LastIndexOf(".")) > 0)
        {
            count = InputFile.Length – start;
            InputFile = InputFile.Remove(start, count);
        }
    }

    /// <summary>
    /// Gets a file extension of a filename.
    /// </summary>
    /// <param name="InputFile">The input file.</param>
    /// <returns>The file extension</returns>
    public static string FileExtension(this string InputFile)
    {
        int start, count;
        if ((start = InputFile.LastIndexOf(".")) > 0)
        {
            count = InputFile.Length – start;
            return InputFile.Substring(start, count);
        }
        return string.Empty;
    }

}

 

Now whenever you use a System.String object, you’ll be able to simply call these methods as if they were part of the System.String class. IE: string MyFileExtension = MyFilePath.FileExtension();

I’m sure I’ll add on to this as I go along.

TI-83 Addition

I’ve added a section to the site called “TI-83″ which contains just a couple of programs I’ve written for my graphing calculator over the years. A lot of these I wrote when I was in high school to assist me on quizzes and homework for algebra II and pre-calc. I’ve been finding myself relying more and more on my graphing calculator recently to solve complex equations–most recently was the Bernoulli Trials equation for my Discreet Mathematics class. Last session in school I damn near wrote a program that solved systems of equations using the Gauss-Jordan method, but then I realized that my graphing calculator already did this for me, so a program was not needed.

They’re all pretty small, but they might be worth grabbing. You’ll have to use your best judgement on using special math characters since keyboards and HTML don’t have them available for input/display. So for example instead of the square root sign that would normally be in a program or on a graphing calculator, I used “sqrt” and for something like the Greek letter Theta, i used <THETA> or (THETA). So the programs won’t port DIRECTLY into your calculator, you’ll have to use your discretion to make any modifications necessary.

Enjoy! *pushes glasses back up on nose with a single finger*

Templatize Tool

I recently wrote up a template engine tool called Templatize. It started as a tool for my girlfriend so she could quickly generate HTML pages from CSV rows for use on eBay, but then quickly grew into a more robust template tool.

Basically it takes a set of input data, containing multiple entities (rows), each with multiple properties (columns), formatted from some type of delimited text file. Then it takes in a master template file and spits out multiple “data-injected” versions of that template.

View the full page here.