Skip to content

Commit 7afb879

Browse files
Improve safety and speed
Speed: nextSlot(false) is now inlined in nextSlot() Safety: next() now throws "NoSuchElementException" when something is actually null
1 parent cbba7dd commit 7afb879

File tree

1 file changed

+20
-12
lines changed

1 file changed

+20
-12
lines changed

src/main/java/me/flame/menus/menu/iterator/MenuIterator.java

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import org.jetbrains.annotations.Nullable;
88

99
import java.util.Iterator;
10+
import java.util.NoSuchElementException;
1011

1112
/**
1213
*
@@ -56,12 +57,18 @@ public MenuIterator(int startingRow, int startingCol,
5657
currentPosition = shiftedPos;
5758
}
5859

59-
//when it becomes empty
60+
// when it becomes empty
6061
return currentPosition;
6162
}
6263

6364
public @Nullable Slot nextSlot() {
64-
return nextSlot(false);
65+
Slot newPos = direction.shift(currentPosition, menu.getRows());
66+
if (newPos.getRow() >= menu.getRows() || newPos.getRow() < 1
67+
|| newPos.getColumn() > 9 || newPos.getColumn() < 1) {
68+
return null;
69+
}
70+
currentPosition = newPos;
71+
return newPos;
6572
}
6673

6774
@Override
@@ -72,12 +79,13 @@ public boolean hasNext() {
7279

7380
@Override
7481
public MenuItem next() {
75-
return menu.getItem(nextSlot());
82+
Slot slot = nextSlot(false);
83+
if (slot == null)
84+
throw new NoSuchElementException("Used MenuIterator#next() but no more items to iterate over");
85+
return menu.getItem(slot);
7686
}
7787

7888
public enum IterationDirection {
79-
80-
8189
HORIZONTAL() {
8290
@Override
8391
Slot shift(Slot oldPos, int maxRows) {
@@ -117,7 +125,7 @@ Slot shift(Slot oldPos, int maxRows) {
117125

118126
@Override
119127
Slot shift(Slot oldPos, int maxRows) {
120-
int row = oldPos.getRow() + 1;
128+
int row = oldPos.getRow() - 1;
121129
if (row < 1) {
122130
row = oldPos.getRow();
123131
}
@@ -130,7 +138,7 @@ Slot shift(Slot oldPos, int maxRows) {
130138
Slot shift(Slot oldPos, int maxRows) {
131139
int row = oldPos.getRow() + 1;
132140
if (row > maxRows) {
133-
row = 6;
141+
row = oldPos.getRow();
134142
}
135143
return new Slot(row, oldPos.getColumn());
136144
}
@@ -140,21 +148,21 @@ Slot shift(Slot oldPos, int maxRows) {
140148
RIGHT_ONLY {
141149
@Override
142150
Slot shift(Slot oldPos, int maxRows) {
143-
int col = oldPos.getColumn() + 1;
151+
int col = oldPos.getColumn()+1;
144152
if (col > 9) {
145-
col = 9;
153+
col = oldPos.getColumn();
146154
}
147155
return new Slot(oldPos.getRow(), col);
148156
}
149157
},
150158

151159

152-
LEFT_ONLY {
160+
LEFT_ONLY{
153161
@Override
154162
Slot shift(Slot oldPos, int maxRows) {
155-
int col = oldPos.getColumn() - 1;
163+
int col = oldPos.getColumn()-1;
156164
if (col < 1) {
157-
col = 1;
165+
col = oldPos.getColumn();
158166
}
159167
return new Slot(oldPos.getRow(), col);
160168
}

0 commit comments

Comments
 (0)