Skip to content

_.any can return incorrect results when native forEach functions are used #177

Closed
@lshearer

Description

@lshearer

When a native forEach function is present, if _.any is called with a list in which the last item does not pass the truth test it will always return false (even if any other items in the list passed the truth test). The problem is that the native forEach function does not short circuit (return breaker; has no effect on it). Therefore, the return result for the call to _.any will be overwritten by the last item.

Suggested fix:

Replace

            if (result = iterator.call(context, value, index, list)) return breaker;

with

            if (result |= iterator.call(context, value, index, list)) return breaker;

in _.any, resulting in:

    var any = _.some = _.any = function (obj, iterator, context) {
        iterator = iterator || _.identity;
        var result = false;
        if (obj == null) return result;
        if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
        each(obj, function (value, index, list) {
            if (result |= iterator.call(context, value, index, list)) return breaker;
        });
        return !!result;
    };

This prevents result from being set to true and then later being overwritten by false.

Edit: because the |= operation returns an integer, to maintain a strictly boolean return type, the return value would need to be !!result

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions