tipsy / j2html

Java to HTML generator. Enjoy typesafe HTML generation.
https://j2html.com/
Apache License 2.0
765 stars 136 forks source link

join doesn't match expected behavior for a join method #169

Closed sagesmith-wf closed 3 years ago

sagesmith-wf commented 3 years ago

Description

The join method doesn't work like a normal join method.

List<String> list = List.of("a", "b", "c");
System.out.println(String.join(", ", list));
// a, b, c

join(", ", true, list.stream().toArray())
// a, b, c,

Suggested fix

You can fix this pretty easily with 4 minor tweaks

package j2html.tags;

public class DomContentJoiner {

    public static UnescapedText join(CharSequence delimiter, boolean fixPeriodAndCommaSpacing, Object... stringOrDomObjects) {
        StringBuilder sb = new StringBuilder();
        // SUGGESTED CHANGE: 1
        for (int i = 0; i < stringOrDomObjects.length; i++) {
            // SUGGESTED CHANGE: 2
            Object o = stringOrDomObjects[i];
            if (o instanceof String) {
                sb.append(((String) o).trim());
            } else if (o instanceof DomContent) {
                sb.append(((DomContent) o).render().trim());
            } else if (o == null) {
                //Discard null objects so iff/iffelse can be used with join
                continue;
            } else {
                throw new RuntimeException("You can only join DomContent and String objects");
            }
            // SUGGESTED CHANGE: 3
            if (i < stringOrDomObjects.length-1) {
                 sb.append(delimiter);
            }
        }
        String joined = sb.toString().trim();
        if (fixPeriodAndCommaSpacing) {
            joined = joined.replaceAll("\\s\\.", ".");
            joined = joined.replaceAll("\\s\\,", ",");
        }
        return new UnescapedText(joined);
    }
}

See: https://github.com/tipsy/j2html/pull/168

sembler commented 3 years ago

PR was reviewed and merged. Thanks!