HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Linq-like functions in JavaScript

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascriptfunctionslinqlike

Problem

Today was my first day working with JavaScript and I tried to implement some Linq-like (C#) functions as extension methods.

I'm pretty new to JavaScript and wanted to ask you for checking my functions and tell me, whether they're good and really usable in productive applications. Or maybe, what I could do better. I don't know whether there is already a library for this; it's primarily for learning purposes.

Array.prototype.where = function * (predicate){
    for(var i=0; i 0;
    for(var i=0; i  0 ? this[0] : null;
    }
    for(var i=0; i = 0) continue;
            already_yielded.push(current_element);
        }else{
            if (already_yielded.indexOf(predicate(current_element)) >= 0) continue;
            already_yielded.push(predicate(current_element));
        }
        yield current_element;
    }
}

Solution

This might not really be an answer, but I suggest you to check out linq.js.
So yes, there is already an implementation of this and you can look at the code to compare and it will help the "learning purposes" you're aiming for.

Example implementation of any :

// Overload:function()
    // Overload:function(predicate)
    Enumerable.prototype.any = function (predicate) {
        predicate = Utils.createLambda(predicate);

        var enumerator = this.getEnumerator();
        try {
            if (arguments.length == 0) return enumerator.moveNext(); // case:function()

            while (enumerator.moveNext()) // case:function(predicate)
            {
                if (predicate(enumerator.current())) return true;
            }
            return false;
        }
        finally {
            Utils.dispose(enumerator);
        }
    };


I personally don't have the required experience in JavaScript to give you my opinion on your implementation. Good luck !

Code Snippets

// Overload:function()
    // Overload:function(predicate)
    Enumerable.prototype.any = function (predicate) {
        predicate = Utils.createLambda(predicate);

        var enumerator = this.getEnumerator();
        try {
            if (arguments.length == 0) return enumerator.moveNext(); // case:function()

            while (enumerator.moveNext()) // case:function(predicate)
            {
                if (predicate(enumerator.current())) return true;
            }
            return false;
        }
        finally {
            Utils.dispose(enumerator);
        }
    };

Context

StackExchange Code Review Q#152785, answer score: 4

Revisions (0)

No revisions yet.