| 739 | } |
| 740 | |
| 741 | function mapEach(arr, fn, useIndex, callback) { |
| 742 | if (!Array.isArray(arr)) { |
| 743 | throw new TypeError('First parameter must be an Array'); |
| 744 | } |
| 745 | callback = callback || noop; |
| 746 | const length = arr.length; |
| 747 | if (length === 0) { |
| 748 | return callback(null, []); |
| 749 | } |
| 750 | const result = new Array(length); |
| 751 | let completed = 0; |
| 752 | const invoke = useIndex ? invokeWithIndex : invokeWithoutIndex; |
| 753 | for (let i = 0; i < length; i++) { |
| 754 | invoke(i); |
| 755 | } |
| 756 | |
| 757 | function invokeWithoutIndex(i) { |
| 758 | fn(arr[i], function mapItemCallback(err, transformed) { |
| 759 | result[i] = transformed; |
| 760 | next(err); |
| 761 | }); |
| 762 | } |
| 763 | |
| 764 | function invokeWithIndex(i) { |
| 765 | fn(arr[i], i, function mapItemCallback(err, transformed) { |
| 766 | result[i] = transformed; |
| 767 | next(err); |
| 768 | }); |
| 769 | } |
| 770 | |
| 771 | function next(err) { |
| 772 | if (err) { |
| 773 | const cb = callback; |
| 774 | callback = noop; |
| 775 | cb(err); |
| 776 | return; |
| 777 | } |
| 778 | if (++completed !== length) { |
| 779 | return; |
| 780 | } |
| 781 | callback(null, result); |
| 782 | } |
| 783 | } |
| 784 | |
| 785 | /** |
| 786 | * @param {Array} arr |