-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcodePositionToIndex.mjs
More file actions
38 lines (31 loc) · 928 Bytes
/
codePositionToIndex.mjs
File metadata and controls
38 lines (31 loc) · 928 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import CodePosition from "./CodePosition.mjs";
/**
* Converts a code position to a string index.
* @kind function
* @name codePositionToIndex
* @param {CodePosition} codePosition Code position.
* @param {string} code Code.
* @returns {number} String index.
* @ignore
*/
export default function codePositionToIndex(codePosition, code) {
if (!(codePosition instanceof CodePosition))
throw new TypeError(
"Argument 1 `codePosition` must be a `CodePosition` instance."
);
if (typeof code !== "string")
throw new TypeError("Argument 2 `code` must be a string.");
if (code === "")
throw new TypeError("Argument 2 `code` must be a populated string.");
let index = 0;
let line = 1;
let column = 1;
while (line < codePosition.line || column < codePosition.column) {
if (code[index] === "\n") {
line++;
column = 1;
} else column++;
index++;
}
return index;
}