Skip to content

Why not support breaking the loop? #3

@nbouvrette

Description

@nbouvrette

One of the major problem with the standard Array.forEach method is that you cannot break it. I have modified your code to support such feature with only a few minor changes and I think it would be most useful to solve many use cases:

var forEach = function (collection, callback, scope) {
    var result = false;
    if (Object.prototype.toString.call(collection) === '[object Object]') {
        for (var prop in collection) {
            if (Object.prototype.hasOwnProperty.call(collection, prop)) {
                result = callback.call(scope, collection[prop], prop, collection);
                if (result !== undefined) {
                    break;
                }
            }
        }
    } else {
        for (var i = 0, len = collection.length; i < len; i++) {
            result = callback.call(scope, collection[i], i, collection);
            if (result !== undefined) {
                break;
            }
        }
    }
    return result;
};

For example you could use it like this:

console.log(forEach([1,2,3], function(number) {
    if (number === 2) {
        return 'You win!';
    }
}));

The result would loop on 1, then ,2 and stop there returning the output.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions