Ever wish JavaScriptSerializer had a non-generic Deserialize method (like DataContractJSONSerializer)?

Well, Rex informed me of the handy MethodInfo.MakeGenericMethod which creates a constructed generic method, allowing us to avoid having to declare the generic types at design time.  So, now we can bolt on a Deserialize method (note, we cache the constructed generic methods) (formatted to appease wordpress)

public static class JavaScriptSerializerExtensions
    {
        private static object _lock = new object();
        private static IDictionary<Type, MethodInfo> _deserializers
               = new Dictionary<Type, MethodInfo>();

        private static MethodInfo GetDeserializeMethod(Type type)
        {
            lock (_lock)
            {
                if (_deserializers.ContainsKey(type)==false)
                {
                    var mi = typeof(JavaScriptSerializer)
                        .GetMethod("Deserialize");
                    _deserializers[type] = mi.MakeGenericMethod(type);
                }
            }
            return _deserializers[type];
        }

        public static object Deserialize(
               this JavaScriptSerializer serializer, Type type, string json)
        {
            return GetDeserializeMethod(type).Invoke(
                serializer, new object[] { json });
        }
    }

Get inspiration from .net’s LINQ in Javascript

When you think about working with enumerable stuff client-side, you can get great inspiration from .net’s awesome LINQ goodness.  For example, if you need a trivial way to sum up items in an array, you can bolt on a “sum” routine onto Arrays.  For example, here’s a small one, which has a default implementation to deal with strings or numbers:

Array.prototype.sum = function (predicate) {
    predicate = predicate || function (match) {
        if (typeof match == "string") {
            return match.length;
        }
        return match;
    };
    var result = 0;
    for (var i = 0; i < this.length; i++) {
        result += predicate(this[i]);
    }
    return result;
};

Here are a couple usage examples:

// Baked-in sum for strings
var array1 = ["hello","world"];
var length = array1.sum());

// Baked-in sum for numbers
var array2 = [10,20,30];
length = array2.sum();

// Custom for custom objects.
var array3 = [{yearsOfExperience:3},{yearsOfExperience:5}];
length = array3.sum(function(match){return match.yearsOfExperience;});

Here’s a Fiddle that demonstrates this (hit F12 in FF, Chrome, IE*+ and look at the console when running):  http://jsfiddle.net/harperj1029/Zeaqa/

Think Linq!