forked from moroshko/react-autosuggest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsectionIterator.js
101 lines (76 loc) · 1.9 KB
/
sectionIterator.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
let data, multipleSections;
function setData(newData) {
data = newData;
multipleSections = (typeof data === 'object');
}
function nextNonEmptySectionIndex(sectionIndex) {
if (sectionIndex === null) {
sectionIndex = 0;
} else {
sectionIndex++;
}
while (sectionIndex < data.length && data[sectionIndex] === 0) {
sectionIndex++;
}
return sectionIndex === data.length ? null : sectionIndex;
}
function prevNonEmptySectionIndex(sectionIndex) {
if (sectionIndex === null) {
sectionIndex = data.length - 1;
} else {
sectionIndex--;
}
while (sectionIndex >= 0 && data[sectionIndex] === 0) {
sectionIndex--;
}
return sectionIndex === -1 ? null : sectionIndex;
}
function next(position) {
let [sectionIndex, itemIndex] = position;
if (multipleSections) {
if (itemIndex === null || itemIndex === data[sectionIndex] - 1) {
sectionIndex = nextNonEmptySectionIndex(sectionIndex);
if (sectionIndex === null) {
return [null, null];
}
return [sectionIndex, 0];
}
return [sectionIndex, itemIndex + 1];
}
if (data === 0 || itemIndex === data - 1) {
return [null, null];
}
if (itemIndex === null) {
return [null, 0];
}
return [null, itemIndex + 1];
}
function prev(position) {
let [sectionIndex, itemIndex] = position;
if (multipleSections) {
if (itemIndex === null || itemIndex === 0) {
sectionIndex = prevNonEmptySectionIndex(sectionIndex);
if (sectionIndex === null) {
return [null, null];
}
return [sectionIndex, data[sectionIndex] - 1];
}
return [sectionIndex, itemIndex - 1];
}
if (data === 0 || itemIndex === 0) {
return [null, null];
}
if (itemIndex === null) {
return [null, data - 1];
}
return [null, itemIndex - 1];
}
function isLast(position) {
return next(position)[1] === null;
}
export default {
setData,
next,
prev,
isLast
};