Skip to content

Commit

Permalink
let generateSlots handle multi-slots
Browse files Browse the repository at this point in the history
  • Loading branch information
HSGamer committed Jul 3, 2024
1 parent 2456b5e commit 55ffb55
Showing 1 changed file with 20 additions and 22 deletions.
42 changes: 20 additions & 22 deletions src/main/java/me/hsgamer/bettergui/util/SlotUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
Expand All @@ -17,7 +15,6 @@ public class SlotUtil {
private static final String POS_X = "position-x";
private static final String POS_Y = "position-y";
private static final String POS_SLOT = "slot";
private static final Pattern RANGE_PATTERN = Pattern.compile("([0-9]+)-([0-9]+)");

private SlotUtil() {
// EMPTY
Expand Down Expand Up @@ -45,10 +42,7 @@ public static List<Integer> getSlots(Map<String, Object> map) {
slots.add((y - 1) * 9 + x - 1);
}
if (map.containsKey(POS_SLOT)) {
slots.addAll(Arrays
.stream(String.valueOf(map.get(POS_SLOT)).split(","))
.map(String::trim)
.flatMap(SlotUtil::generateSlots).collect(Collectors.toList()));
slots.addAll(generateSlots(String.valueOf(map.get(POS_SLOT))).collect(Collectors.toList()));
}
return slots;
}
Expand All @@ -61,20 +55,24 @@ public static List<Integer> getSlots(Map<String, Object> map) {
* @return the stream of slots
*/
public static Stream<Integer> generateSlots(String input) {
Matcher matcher = RANGE_PATTERN.matcher(input);
if (matcher.matches()) {
int s1 = Integer.parseInt(matcher.group(1));
int s2 = Integer.parseInt(matcher.group(2));
if (s1 <= s2) {
return IntStream.rangeClosed(s1, s2).boxed();
} else {
return IntStream.rangeClosed(s2, s1).boxed().sorted(Collections.reverseOrder());
}
}

return Validate.getNumber(input)
.map(BigDecimal::intValue)
.map(Stream::of)
.orElseGet(Stream::empty);
return Arrays.stream(input.split(","))
.map(String::trim)
.flatMap(rawSlot -> {
String[] rangeSplit = rawSlot.split("-", 2);
if (rangeSplit.length == 2) {
Optional<Integer> start = Validate.getNumber(rangeSplit[0]).map(BigDecimal::intValue);
Optional<Integer> end = Validate.getNumber(rangeSplit[1]).map(BigDecimal::intValue);
if (start.isPresent() && end.isPresent()) {
return IntStream.rangeClosed(start.get(), end.get()).boxed();
} else {
return Stream.empty();
}
} else {
return Validate.getNumber(input)
.map(BigDecimal::intValue)
.map(Stream::of)
.orElseGet(Stream::empty);
}
});
}
}

0 comments on commit 55ffb55

Please sign in to comment.