Showing posts with label extension methods. Show all posts
Showing posts with label extension methods. Show all posts

Wednesday, October 13, 2010

Some handy Javascript array methods

Working with javascript arrays today, I found some handy functions:

- Creating an array :
var ray = [];

- Joining two arrays :
var resultArray = ArrayOne.concat(ArrayTwo);

- Getting only unique items in an array :
(Jquery has a unique function, but it does not work on strings / numbers)
Array.prototype.unique = function() {
var result = new Array();
o: for (var i = 0, n = this.length; i < n; i++) {
for (var x = 0, y = result.length; x < y; x++) {
if (result[x] == this[i]) {
continue o;
}
}
result[result.length] = this[i];
}
return r;
}


- For each in JavaScript(using JQuery):
(although JavaScript has for (item in collection) functionality, it is not useful as it also iterates through the methods of the object.)
$.each(collection, function(index, value) { alert(index + ' : ' + value); });




- Bonus JavaScript : Splitting a string by multiple delimiters :
use a regular expression :
var result = myString.split(/[DELIMITERS]+/);
just replace DELIMITERS with the delimiters you want (one character delimiters)

Tuesday, October 6, 2009

Good old VB functions in c# Left, Mid, Right

Missing the good old string functions in c# I wanted to recreate them.
This is my solution where they are resurrected as extension methods.


public static class StringHelper
{
    public static string Right(this String source, int length)
    {
        if (source.Length == 0 || length <= 0)
        {
        return "";
        }

        return source.Substring(source.Length - length, length);
    }

    public static string Left(this String source, int length)
    {
        if (source.Length == 0 || length <= 0)
        {
        return "";
        }

        return source.Substring(0, length);
    }

    public static string Mid(this string source, int startIndex, int length)
    {
        if (source.Length == 0 || length <= 0 || startIndex < 0)
        {
        return "";
        }
        return source.Substring(startIndex, length);
    }

    public static string Mid(this string source, int startIndex)
    {
        if (source.Length == 0 || startIndex < 0)
        {
        return "";
        }
        return source.Substring(startIndex);
    }
}


To keep the code from giving errors I check for the length parameter,
if this is not what you want, you can throw an argumentexception for example ...