Refactor and simplify member list code
This commit is contained in:
		@@ -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;
 | 
			
		||||
        } 
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
		Reference in New Issue
	
	Block a user