From 6eb1ecc2120f999e4b418ad1633760e0dbd3c2e3 Mon Sep 17 00:00:00 2001 From: Sxtanna Date: Sat, 25 Jul 2020 22:35:56 -0400 Subject: [PATCH] Implemented general purpose table utility --- .../me/clip/placeholderapi/util/Format.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/main/java/me/clip/placeholderapi/util/Format.java diff --git a/src/main/java/me/clip/placeholderapi/util/Format.java b/src/main/java/me/clip/placeholderapi/util/Format.java new file mode 100644 index 0000000..20967f4 --- /dev/null +++ b/src/main/java/me/clip/placeholderapi/util/Format.java @@ -0,0 +1,58 @@ +package me.clip.placeholderapi.util; + +import org.jetbrains.annotations.NotNull; + +import java.util.List; +import java.util.Optional; + +import static java.lang.Math.max; +import static java.lang.Math.min; +import static java.util.Arrays.stream; +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.toList; +import static java.util.stream.IntStream.range; + +/** + * For the record, I am not sorry. + */ +public final class Format +{ + + private Format() + {} + + + public enum Align + { + LEFT, RIGHT + } + + + @NotNull + public static Optional> tablify(@NotNull final Align align, @NotNull final List> rows) + { + return findSpacing(rows) + .map(spacing -> buildFormat(align, spacing)) + .map(format -> rows.stream() + .map(row -> String.format(format, row.toArray()).substring(align == Align.RIGHT ? 2 : 0)) + .collect(toList())); + } + + + @NotNull + private static String buildFormat(@NotNull final Align align, @NotNull final int[] spacing) + { + return stream(spacing) + .mapToObj(space -> "%" + (align == Align.LEFT ? "-" : "") + (space + 2) + "s") + .collect(joining()); + } + + @NotNull + private static Optional findSpacing(@NotNull final List> rows) + { + return rows.stream() + .map(row -> row.stream().mapToInt(String::length).toArray()) + .reduce((l, r) -> range(0, min(l.length, r.length)).map(i -> max(l[i], r[i])).toArray()); + } + +}