mihaifm / linq

linq.js - LINQ for JavaScript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bug: Doesn't allow defaultValue = undefined in firstOrDefault

bendtherules opened this issue · comments

Enumerable.prototype.firstOrDefault = function (predicate, defaultValue) {
        if (predicate) {
            if (typeof predicate === Types.Function || typeof Utils.createLambda(predicate) === Types.Function)
                return this.where(predicate).firstOrDefault(null, defaultValue);

                defaultValue = predicate;
        }

        defaultValue = defaultValue || null; // THIS LINE
        ...

Maybe we should remove this line from firstOrDefault to allow undefined as default value?

It is specially important because the user might pass in undefined explicitly for the parameter defaultValue (which is the conventional missing value in JS), and this undefined value will get overloaded with null.

Even the type definition doesnt indicate that the return type might be T or null. In fact, type definition doesn't allow passing in null explicitly as defaultValue (which would make things more explicit and understandable for users).

The user has no way of knowing this unless they actually look into the code.

You seem to be using an earlier version...can you check (in the latest version from git) if you can pass null as the defaultValue? You should be able to do so. Otherwise we may need to fix it.

You are correct, the type definition is fixed in master.
But the problem with the logic still exists https://github.com/mihaifm/linq/blob/master/linq.js#L1865 . You still can't set undefined as defaultvalue. I would suggesting changing the default of defaultValue to undefined from null, as that is the common way to represent missing in JS.