-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
61 lines (47 loc) · 1.5 KB
/
index.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
function iterateArrayLike(array, onEach) {
const itemCount = array.length;
let index = 0;
while (index < itemCount && onEach(array[index], index, array) !== false) {
++index;
}
return { complete: index === itemCount };
}
function getIterateIterator(iteratable) {
if(iteratable[Symbol.iterator]) {
return iteratable[Symbol.iterator]();
}
if (iteratable.constructor === Object) {
return Object.entries(iteratable)[Symbol.iterator]();
}
return null;
}
function iterateIterator(iterator, iteratable, onEach) {
let step = iterator.next();
while (!step.done && onEach(step.value[1], step.value[0], iteratable) !== false) {
step = iterator.next();
}
return { complete: step.done };
}
function iterateSetIterator(iterator, set, onEach) {
let step = iterator.next();
while (!step.done && onEach(step.value, step.value, set) !== false) {
step = iterator.next();
}
return { complete: step.done };
}
module.exports = function iterate(iteratable, onEach) {
// array likes (eg. strings)
if (iteratable.length && iteratable[Symbol.iterator]) {
return iterateArrayLike(iteratable, onEach);
} else {
const iterator = getIterateIterator(iteratable);
if (!iterator || !iterator.next) {
throw new Error('First parameter needs to be plain Object or an iteratable.');
}
if (iteratable instanceof Set) {
return iterateSetIterator(iterator, iteratable, onEach);
} else {
return iterateIterator(iterator, iteratable, onEach);
}
}
};