This project has moved. For the latest updates, please go here.
1
Vote

FirstOrDefault implementation is wrong

description

Just yesterday I added this library to my project from nuget and I noticed that the implementation of both FirstOrDefault and LastOrDefault are both wrong (in that they don't behave the same way as their .Net counterparts) ...

We should be returning the first / last item that returns true for the given function instead it appears to just return the first item in the collection.

Suggested fix ...

Update these functions from:
FirstOrDefault: function(defaultValue) {
    return this.First() || defaultValue;
},
LastOrDefault: function(defaultValue) {
    return this.Last() || defaultValue;
}
... to read ...
FirstOrDefault: function(defaultValue, clause) {
    return this.First(clause) || defaultValue;
},
LastOrDefault: function(defaultValue, clause) {
    return this.Last(clause) || defaultValue;
}
... its also logically incorrect to have FirstOrDefault depend on First in this manner so the better implementation may be to swap their implementations around where first should probably look something like this ...
First: function(clause) {
    if (clause != null) {
        var result = this.FirstOrDefault(null, clause);
        if(result == null) 
              throw new Exception("Nope!");
    }
    else {
        // If no clause was specified, then return the First element in the Array
        if (this.items.length > 0)
            return this.items[0];
        else
            throw new Exception("Nope!"); 
    }
}

comments