Modularization, some rudimentary cleanup
This commit is contained in:
37
discord-utils.mjs
Normal file
37
discord-utils.mjs
Normal file
@@ -0,0 +1,37 @@
|
||||
|
||||
export function split_discord_message(text) {
|
||||
const MAX = 1900; // maximum payload size
|
||||
const MIN = 100; // avoid tiny chunks
|
||||
const chunks = [];
|
||||
let start = 0;
|
||||
|
||||
while (start < text.length) {
|
||||
let end = Math.min(start + MAX, text.length);
|
||||
|
||||
// Try to break on a newline first, then on a space
|
||||
if (end < text.length) {
|
||||
const nl = text.lastIndexOf('\n', end);
|
||||
const sp = text.lastIndexOf(' ', end);
|
||||
const splitPos = Math.max(nl, sp);
|
||||
if (splitPos > start) end = splitPos + 1; // keep the delimiter
|
||||
}
|
||||
|
||||
// If the chunk is too short, pull in the next delimiter
|
||||
if (end - start < MIN && end < text.length) {
|
||||
const nextNL = text.indexOf('\n', end);
|
||||
const nextSP = text.indexOf(' ', end);
|
||||
const nextPos = Math.min(
|
||||
nextNL === -1 ? Infinity : nextNL,
|
||||
nextSP === -1 ? Infinity : nextSP
|
||||
);
|
||||
if (nextPos !== Infinity && nextPos < text.length) {
|
||||
end = nextPos + 1;
|
||||
}
|
||||
}
|
||||
|
||||
chunks.push(text.slice(start, end));
|
||||
start = end;
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
Reference in New Issue
Block a user