Skip to content

Commit 37475b2

Browse files
committed
Improve LazyUtilities#sortChoicesFuzzy(...)
1 parent cf198f4 commit 37475b2

File tree

1 file changed

+18
-17
lines changed

1 file changed

+18
-17
lines changed

src/main/java/xyz/srnyx/lazylibrary/utility/LazyUtilities.java

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import com.freya02.botcommands.api.application.slash.autocomplete.AutocompleteAlgorithms;
44
import com.freya02.botcommands.api.pagination.paginator.PaginatorBuilder;
55

6+
import me.xdrop.fuzzywuzzy.model.BoundExtractedResult;
7+
68
import net.dv8tion.jda.api.Permission;
79
import net.dv8tion.jda.api.entities.Member;
810
import net.dv8tion.jda.api.entities.User;
@@ -21,6 +23,7 @@
2123

2224
import java.util.Collection;
2325
import java.util.List;
26+
import java.util.function.Function;
2427

2528

2629
/**
@@ -65,24 +68,22 @@ public static boolean userHasChannelPermission(@NotNull Interaction interaction,
6568
@NotNull
6669
public static List<Command.Choice> sortChoicesFuzzy(@NotNull CommandAutoCompleteInteractionEvent event, @NotNull Collection<Command.Choice> collection) {
6770
final OptionType type = event.getFocusedOption().getType();
71+
final Function<BoundExtractedResult<Command.Choice>, Command.Choice> mapping = switch (type) {
72+
case STRING -> BoundExtractedResult::getReferent;
73+
case INTEGER -> result -> {
74+
final Command.Choice choice = result.getReferent();
75+
final Long value = Mapper.toLong(choice.getAsString());
76+
return value == null ? null : new Command.Choice(choice.getName(), value);
77+
};
78+
case NUMBER -> result -> {
79+
final Command.Choice choice = result.getReferent();
80+
final Double value = Mapper.toDouble(choice.getAsString());
81+
return value == null ? null : new Command.Choice(choice.getName(), value);
82+
};
83+
default -> throw new IllegalArgumentException("Invalid autocompletion option type: " + type);
84+
};
6885
return AutocompleteAlgorithms.fuzzyMatching(collection, Command.Choice::getName, event).stream()
69-
.map(result -> {
70-
final Command.Choice choice = result.getReferent();
71-
final String name = choice.getName();
72-
final String value = choice.getAsString();
73-
return switch (type) {
74-
case STRING -> new Command.Choice(name, value);
75-
case INTEGER -> {
76-
final Long valueLong = Mapper.toLong(value);
77-
yield valueLong == null ? null : new Command.Choice(name, valueLong);
78-
}
79-
case NUMBER -> {
80-
final Double valueDouble = Mapper.toDouble(value);
81-
yield valueDouble == null ? null : new Command.Choice(name, valueDouble);
82-
}
83-
default -> throw new IllegalArgumentException("Invalid autocompletion option type: " + type);
84-
};
85-
})
86+
.map(mapping)
8687
.toList();
8788
}
8889

0 commit comments

Comments
 (0)