Files
test-repo/src/utils/skip-newline.js
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

53 lines
1.4 KiB
JavaScript
Raw Normal View History

2024-10-01 19:45:37 +08:00
/** @import {SkipOptions} from "./skip.js" */
/**
* Check if a character is a newline character
* @param {string} character
* @returns {boolean}
*/
const isNewlineCharacter = (character) =>
character === "\n" ||
character === "\r" ||
character === "\u2028" ||
character === "\u2029";
// 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
* @returns {number | false}
*/
2023-02-10 14:24:38 +08:00
function skipNewline(text, startIndex, options) {
const backwards = Boolean(options?.backwards);
if (startIndex === false) {
return false;
}
2023-02-10 14:24:38 +08:00
const character = text.charAt(startIndex);
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;
}
if (isNewlineCharacter(character)) {
2023-02-10 14:24:38 +08:00
return startIndex - 1;
}
} 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;
}
if (isNewlineCharacter(character)) {
2023-02-10 14:24:38 +08:00
return startIndex + 1;
}
}
2023-02-10 14:24:38 +08:00
return startIndex;
}
export default skipNewline;