This repository has been archived by the owner on Nov 4, 2022. It is now read-only.
forked from jashkenas/underscore
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathiterateDW.js
86 lines (83 loc) · 2.85 KB
/
iterateDW.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
function closeIter(iter) {
if (iter && 'close' in iter) {
iter.close();
}
}
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
var getLength = require('./property')('length');
var isArrayLike = function(collection) {
var length = getLength(collection);
return typeof length === 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
};
module.exports = function iterateDW(collection, callback, firstElfn) {
var iter,
keys,
value,
result,
length,
i,
count = 0,
callfirstElfn = firstElfn && function (v) {
if (firstElfn) {
callfirstElfn = null;
firstElfn(v);
return true;
}
};
if (typeof collection === 'object' && collection !== null) {
if ('iterator' in collection && typeof collection.iterator === 'function') {
// suppose that collection is DW collection
iter = collection.iterator();
while (iter.hasNext()) {
value = iter.next();
if (callfirstElfn && callfirstElfn(value)) {
count++;
continue;
}
result = callback(value, count++, collection);
if (result === false) {
closeIter(iter);
return result;
}
}
closeIter(iter);
} else if ('hasNext' in collection && typeof collection.hasNext === 'function') {
// suppose that collection is DW iterator
while (collection.hasNext()) {
value = collection.next();
if (callfirstElfn && callfirstElfn(value)) {
count++;
continue;
}
result = callback(value, count++, collection);
if (result === false) {
return result;
}
}
closeIter(collection);
} else if (isArrayLike(collection)) {
// suppose that collection is array
for (i = 0, length = collection.length; i < length; i++) {
if (callfirstElfn && callfirstElfn(collection[i])) {
continue;
}
result = callback(collection[i], i, collection);
if (result === false) {
return result;
}
}
} else {
// suppose that collection is plain object
keys = require('./keys')(collection);
for (i = 0, length = keys.length; i < length; i++) {
if (callfirstElfn && callfirstElfn(collection[keys[i]])) {
continue;
}
result = callback(collection[keys[i]], keys[i], collection);
if (result === false) {
return result;
}
}
}
}
};