Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

codeframe.js 1.3KB

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