Repositorio del curso CCOM4030 el semestre B91 del proyecto kilometro0

index.js 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. var isCallable = require('is-callable');
  3. var toStr = Object.prototype.toString;
  4. var hasOwnProperty = Object.prototype.hasOwnProperty;
  5. var forEachArray = function forEachArray(array, iterator, receiver) {
  6. for (var i = 0, len = array.length; i < len; i++) {
  7. if (hasOwnProperty.call(array, i)) {
  8. if (receiver == null) {
  9. iterator(array[i], i, array);
  10. } else {
  11. iterator.call(receiver, array[i], i, array);
  12. }
  13. }
  14. }
  15. };
  16. var forEachString = function forEachString(string, iterator, receiver) {
  17. for (var i = 0, len = string.length; i < len; i++) {
  18. // no such thing as a sparse string.
  19. if (receiver == null) {
  20. iterator(string.charAt(i), i, string);
  21. } else {
  22. iterator.call(receiver, string.charAt(i), i, string);
  23. }
  24. }
  25. };
  26. var forEachObject = function forEachObject(object, iterator, receiver) {
  27. for (var k in object) {
  28. if (hasOwnProperty.call(object, k)) {
  29. if (receiver == null) {
  30. iterator(object[k], k, object);
  31. } else {
  32. iterator.call(receiver, object[k], k, object);
  33. }
  34. }
  35. }
  36. };
  37. var forEach = function forEach(list, iterator, thisArg) {
  38. if (!isCallable(iterator)) {
  39. throw new TypeError('iterator must be a function');
  40. }
  41. var receiver;
  42. if (arguments.length >= 3) {
  43. receiver = thisArg;
  44. }
  45. if (toStr.call(list) === '[object Array]') {
  46. forEachArray(list, iterator, receiver);
  47. } else if (typeof list === 'string') {
  48. forEachString(list, iterator, receiver);
  49. } else {
  50. forEachObject(list, iterator, receiver);
  51. }
  52. };
  53. module.exports = forEach;