How to make Extension Method

Example / aggregate

Linq.Object.prototype.SimpleSum = function()
{
    var enumerator = this.GetEnumerator();
    var sum = 0;
    while (enumerator.MoveNext())
    {
        sum += enumerator.Current;
    }
    return sum;
}

E.Range(1,10).SimpleSum(); // 55

Example / selector

Linq.Object.prototype.SimpleSum2 = function(selector)
{
    selector = (selector == null)
        ? Linq.Utils.CreateFunctor(selector)
        : function(x) { return x; };

    var enumerator = this.GetEnumerator();
    var sum = 0;
    var index = 0;
    while (enumerator.MoveNext())
    {
        sum += selector(enumerator.Current, index++);
    }
    return sum;
}
E.Repeat(2, 5).SimpleSum2("value,index=>value*index"); // 20

Example / return Linq.Object

Linq.Object.prototype.WithIndex = function()
{
    var source = this;

    return new Linq.Object(function()
    {
        var enumerator = source.GetEnumerator();
        var index = 0;

        return new Linq.Enumerator(function()
        {
            if (enumerator.MoveNext())
            {
                this.Current = { Value: enumerator.Current, Index: index++ };
                return true;
            }
            else
            {
                return false;
            }
        });
    });
}

Example / use Linq Method

Linq.Object.prototype.WithIndex2 = function()
{
    return this.Select(function(value, index) { return { Value: value, Index: index} });
}

Linq.Object.prototype.SimpleSum3 = function()
{
    return this.Aggregate(function(a, b) { a + b });
}

Last edited Apr 4, 2009 at 3:28 AM by neuecc, version 2

Comments

No comments yet.