2024-10-01 19:45:37 +08:00
|
|
|
/** @import {SkipOptions} from "./skip.js" */
|
2022-01-31 00:45:58 +09:00
|
|
|
|
2025-11-01 13:02:08 +08:00
|
|
|
/**
|
|
|
|
|
* Check if a character is a newline character
|
|
|
|
|
* @param {string} character
|
|
|
|
|
* @returns {boolean}
|
|
|
|
|
*/
|
|
|
|
|
const isNewlineCharacter = (character) =>
|
|
|
|
|
character === "\n" ||
|
|
|
|
|
character === "\r" ||
|
|
|
|
|
character === "\u2028" ||
|
|
|
|
|
character === "\u2029";
|
|
|
|
|
|
2022-01-31 00:45:58 +09:00
|
|
|
// This one doesn't use the above helper function because it wants to
|
|
|
|
|
// test \r\n in order and `skip` doesn't support ordering and we only
|
|
|
|
|
// want to skip one newline. It's simple to implement.
|
|
|
|
|
/**
|
|
|
|
|
* @param {string} text
|
2023-02-10 14:24:38 +08:00
|
|
|
* @param {number | false} startIndex
|
|
|
|
|
* @param {SkipOptions=} options
|
2022-01-31 00:45:58 +09:00
|
|
|
* @returns {number | false}
|
|
|
|
|
*/
|
2023-02-10 14:24:38 +08:00
|
|
|
function skipNewline(text, startIndex, options) {
|
|
|
|
|
const backwards = Boolean(options?.backwards);
|
|
|
|
|
if (startIndex === false) {
|
2022-01-31 00:45:58 +09:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
2023-02-10 14:24:38 +08:00
|
|
|
const character = text.charAt(startIndex);
|
2022-01-31 00:45:58 +09:00
|
|
|
if (backwards) {
|
|
|
|
|
// We already replace `\r\n` with `\n` before parsing
|
2022-10-22 23:33:08 +08:00
|
|
|
/* c8 ignore next 3 */
|
2023-02-10 14:24:38 +08:00
|
|
|
if (text.charAt(startIndex - 1) === "\r" && character === "\n") {
|
|
|
|
|
return startIndex - 2;
|
2022-01-31 00:45:58 +09:00
|
|
|
}
|
2025-11-01 13:02:08 +08:00
|
|
|
if (isNewlineCharacter(character)) {
|
2023-02-10 14:24:38 +08:00
|
|
|
return startIndex - 1;
|
2022-01-31 00:45:58 +09:00
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
// We already replace `\r\n` with `\n` before parsing
|
2022-10-22 23:33:08 +08:00
|
|
|
/* c8 ignore next 3 */
|
2023-02-10 14:24:38 +08:00
|
|
|
if (character === "\r" && text.charAt(startIndex + 1) === "\n") {
|
|
|
|
|
return startIndex + 2;
|
2022-01-31 00:45:58 +09:00
|
|
|
}
|
2025-11-01 13:02:08 +08:00
|
|
|
if (isNewlineCharacter(character)) {
|
2023-02-10 14:24:38 +08:00
|
|
|
return startIndex + 1;
|
2022-01-31 00:45:58 +09:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-02-10 14:24:38 +08:00
|
|
|
return startIndex;
|
2022-01-31 00:45:58 +09:00
|
|
|
}
|
|
|
|
|
|
2022-02-28 11:12:37 +08:00
|
|
|
export default skipNewline;
|