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