-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathutils.js
61 lines (59 loc) · 1.46 KB
/
utils.js
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// get the total length, number of lines, and length of the last line of a string
export const get_offsets = str => {
const { length } = str;
let lines = 1;
let last = 0;
for (let i = 0; i < length; i++) {
if (str[i] === '\n') {
lines++;
last = 0;
} else {
last++;
}
}
return { length, lines, last };
};
// dedent a script block, and get offsets necessary to later adjust linting messages about the block
export const dedent_code = str => {
let indentation = '';
for (let i = 0; i < str.length; i++) {
const char = str[i];
if (char === '\n' || char === '\r') {
indentation = '';
} else if (char === ' ' || char === '\t') {
indentation += str[i];
} else {
break;
}
}
const { length } = indentation;
let dedented = '';
const offsets = [];
const total_offsets = [0];
for (let i = 0; i < str.length; i++) {
if (i === 0 || str[i - 1] === '\n') {
if (str.slice(i, i + length) === indentation) {
i += length;
offsets.push(length);
} else {
offsets.push(0);
}
total_offsets.push(total_offsets[total_offsets.length - 1] + offsets[offsets.length - 1]);
if (i >= str.length) {
break;
}
}
dedented += str[i];
}
return { dedented, offsets: { offsets, total_offsets }, indentation };
};
// get character offsets of each line in a string
export const get_line_offsets = str => {
const offsets = [-1];
for (let i = 0; i < str.length; i++) {
if (str[i] === '\n') {
offsets.push(i);
}
}
return offsets;
};