Remake cut feature to be simpler to use and avoid bugs, fixes #35

This commit is contained in:
Jean Viscogliosi-Pate 2025-06-27 20:29:04 -07:00
parent 856240d944
commit 1cacf903dc
1 changed files with 18 additions and 22 deletions

View File

@ -230,7 +230,7 @@ function replaceExceptions(options) {
/* Replaces cut statements with cuts */ /* Replaces cut statements with cuts */
function replaceCuts() { function replaceCuts() {
const searchTerm = /cut\/([^\/]+)\/(-?[\d]+)\/(?:(-?[\d]+)\/)?/i; const searchTerm = /cut\/([^\/]+)\/(off|only) (first|last) ([1-9][0-9]*)\//i;
walk(document.body, searchTerm, null, cutMethod); walk(document.body, searchTerm, null, cutMethod);
} }
@ -379,31 +379,27 @@ function cutMethod(node, searchTerm, unused) {
const match = node.nodeValue.match(searchTerm); const match = node.nodeValue.match(searchTerm);
if (match == null) { return; } if (match == null) { return; }
const target = match[1]; const target = match[1];
let start = Number(match[2]); const length = target.length
let end = Number(match[3]); const isOnly = match[2] == "only";
const isFirst = match[3] == "first";
const index = Number(match[4]);
if (isNaN(end)) { let start, end;
if (start < 0) { // Cut off from the right side if (isOnly) {
end = target.length + start; if (isFirst) { // only first n
start = 0; start = 0;
} else { // Cut off from the left side end = Math.min(index, length - 1);
end = target.length; } else { // only last n
start = Math.max(length - index, 1);
end = length;
} }
} else { } else {
const isNegStart = (start < 0) || ((start == 0) && (end < 0)); if (isFirst) { // off first n
if (isNegStart) { // Starting from the right, move by end start = Math.min(index, length - 1);;
const mod = start; end = length;
start = target.length + mod; } else { // off last n
end = target.length + mod + end; start = 0;
} else { // Starting from the left, move by end end = Math.max(length - index, 1);
end = start + end;
}
// Start should always be less than end
if (start > end) {
const greater = start;
start = end;
end = greater;
} }
} }