-
Notifications
You must be signed in to change notification settings - Fork 11
Open
Description
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
Labels
No labels