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