Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why not support breaking the loop? #3

Open
nbouvrette opened this issue Jun 12, 2016 · 2 comments
Open

Why not support breaking the loop? #3

nbouvrette opened this issue Jun 12, 2016 · 2 comments

Comments

@nbouvrette
Copy link

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.

@toddmotto
Copy link
Owner

Hey Nicolas! Yeah, I love the idea of doing this, but it would go against the spec of forEach, and if you need to break, you'll likely want to use some or every rather than forEach to use the right method for the task.

@nbouvrette
Copy link
Author

It all depends on what is your definition of forEach. I personaly tihnk that the JavaScript definition is quite limited. You can check PHP's foreach which is quite more flexible. In any case I'm tired of the boilerplate required in JavaScript, I created my own 20 lines repo for those who also feel the pain :) https://github.com/nbouvrette/forEach

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants