I’m experimenting with functional-style Javascript and have encountered an interesting situation. I have a foreach function that takes a collection and function object:
var Utils = {};
// Applies a functor to each item in a collection.
Utils.foreach = function(collection, functor)
{
for (var i = 0; i < collection.length; i++)
{
functor(collection[i]);
}
};
This is cool. However now I want to implement another function:
// Checks if a collection contains an item.
Utils.has = function(collection, item)
{
Utils.foreach(collection, function(obj) {
if (item === obj) {
return true; // How to force a return from the foreach function?
}
});
return false;
};
As you can see I can’t implement the “has” function because my return statement doesn’t break the iteration.
Can someone recommend a solution for this problem?
I guess what you want is not actually
forEach, but rathersome(other languages call itany). The couterpart isevery(orallin other languages). You’ll find an example implementation on MDC.