collection-utils.js 870 B

12345678910111213141516171819
  1. "use strict";
  2. var utils = module.exports = {};
  3. /**
  4. * Loops through the collection and calls the callback for each element. if the callback returns truthy, the loop is broken and returns the same value.
  5. * @public
  6. * @param {*} collection The collection to loop through. Needs to have a length property set and have indices set from 0 to length - 1.
  7. * @param {function} callback The callback to be called for each element. The element will be given as a parameter to the callback. If this callback returns truthy, the loop is broken and the same value is returned.
  8. * @returns {*} The value that a callback has returned (if truthy). Otherwise nothing.
  9. */
  10. utils.forEach = function(collection, callback) {
  11. for(var i = 0; i < collection.length; i++) {
  12. var result = callback(collection[i]);
  13. if(result) {
  14. return result;
  15. }
  16. }
  17. };