Posted By

adrusi on 04/21/11


Tagged

foreach skel each skeljs


Versions (?)

Skel `each`


 / Published in: JavaScript
 

  1. _.mixin([_.ARRAY, _.OBJECT], {
  2. each: function(collection, iterator) {
  3. var error = [];
  4. if (collection == null) error.push("_.each requires a collection parameter");
  5. if (typeof collection !== "object") error.push("_.each expects hash or array as first argument");
  6. if (iterator == null) error.push("_.each requires an iterator parameter (2nd parameter)");
  7. if (error.length > 0) {
  8. throw new Error(error.join(". "));
  9. return;
  10. }
  11. switch (iterator.length) { // the number of arguments that the iterator accepts
  12. case 0:
  13. for (var key in collection) {
  14. if (collection.hasOwnProperty(key)) {
  15. iterator.call(collection[key]);
  16. }
  17. }
  18. break;
  19. case 1:
  20. for (var key in collection) {
  21. if (collection.hasOwnProperty(key)) {
  22. iterator(collection[key]);
  23. }
  24. }
  25. break;
  26. case 2:
  27. for (var key in collection) {
  28. if (collection.hasOwnProperty(key)) {
  29. iterator(key, collection[key]);
  30. }
  31. }
  32. break;
  33. }
  34. return collection;
  35. }
  36. });

Report this snippet  

You need to login to post a comment.