MCPcopy Index your code
hub / github.com/XIU2/UserScript / calculatePositionFromLineColumn

Function calculatePositionFromLineColumn

Autopage.user.js:2768–2793  ·  view source on GitHub ↗

* 根据行号和列号计算字符串中的 position 位置 * @param {string} text - 完整的文本内容 * @param {number} line - 行号(从1开始) * @param {number} column - 列号(从1开始) * @returns {number} position 位置(从0开始)

(text, line, column)

Source from the content-addressed store, hash-verified

2766 * @returns {number} position 位置(从0开始)
2767 */
2768 function calculatePositionFromLineColumn(text, line, column) {
2769 if (!text || line < 1 || column < 1) {
2770 return -1;
2771 }
2772
2773 const lines = text.split('\n');
2774
2775 // 如果指定行超过文本行数,返回-1
2776 if (line > lines.length) {
2777 return -1;
2778 }
2779
2780 let position = 0;
2781
2782 // 计算前 (line-1) 行的总长度(包括换行符)
2783 for (let i = 0; i < line - 1; i++) {
2784 position += lines[i].length + 1; // +1 表示换行符
2785 }
2786
2787 // 计算当前行的列位置(列号从1开始,position从0开始)
2788 // 注意:列号不能超过当前行的长度+1(+1表示可以指向行尾)
2789 const currentLine = lines[line - 1];
2790 const columnPosition = Math.min(column - 1, currentLine.length);
2791
2792 return position + columnPosition;
2793 }
2794
2795 // 自定义的 stringify 函数,将 [ ] 内的元素从默认的 换行显示 格式化为 一行显示,用于显示自定义翻页规则等给用户看的场景
2796 function customStringify(obj) {

Callers 1

customRulesFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected