UNPKG

1.28 kBJavaScriptView Raw
1/* @flow */
2
3const range = 2
4
5export function generateCodeFrame (
6 source: string,
7 start: number = 0,
8 end: number = source.length
9): string {
10 const lines = source.split(/\r?\n/)
11 let count = 0
12 const res = []
13 for (let i = 0; i < lines.length; i++) {
14 count += lines[i].length + 1
15 if (count >= start) {
16 for (let j = i - range; j <= i + range || end > count; j++) {
17 if (j < 0 || j >= lines.length) continue
18 res.push(`${j + 1}${repeat(` `, 3 - String(j + 1).length)}| ${lines[j]}`)
19 const lineLength = lines[j].length
20 if (j === i) {
21 // push underline
22 const pad = start - (count - lineLength) + 1
23 const length = end > count ? lineLength - pad : end - start
24 res.push(` | ` + repeat(` `, pad) + repeat(`^`, length))
25 } else if (j > i) {
26 if (end > count) {
27 const length = Math.min(end - count, lineLength)
28 res.push(` | ` + repeat(`^`, length))
29 }
30 count += lineLength + 1
31 }
32 }
33 break
34 }
35 }
36 return res.join('\n')
37}
38
39function repeat (str, n) {
40 let result = ''
41 while (true) { // eslint-disable-line
42 if (n & 1) result += str
43 n >>>= 1
44 if (n <= 0) break
45 str += str
46 }
47 return result
48}