Refactor and simplify member list code

This commit is contained in:
Ske
2020-07-07 20:57:22 +02:00
parent 299f6b2edf
commit 467b95b1b1
10 changed files with 367 additions and 349 deletions

View File

@@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace PluralKit.Core
@@ -56,5 +58,36 @@ namespace PluralKit.Core
// so we remove 'em all :)
return Regex.Replace(input, " *\n", "\n");
}
public static IReadOnlyList<string> JoinPages(IEnumerable<string> input, int characterLimit) =>
JoinPages(input, _ => characterLimit);
public static IReadOnlyList<string> JoinPages(IEnumerable<string> input, Func<int, int> characterLimitByPage)
{
var output = new List<string>();
var buf = new StringBuilder();
foreach (var s in input)
{
var limit = characterLimitByPage.Invoke(output.Count);
// Would adding this string put us over the limit?
// (note: don't roll over if the buffer's already empty; this means an individual section is above the character limit. todo: truncate, then?)
if (buf.Length > 0 && buf.Length + s.Length > limit)
{
// If so, "roll over" (before adding the string to the buffer)
output.Add(buf.ToString());
buf.Clear();
}
buf.Append(s);
}
// We most likely have something left over, so add that in too
if (buf.Length > 0)
output.Add(buf.ToString());
return output;
}
}
}