getGeneratedSourceInfo.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /**
  7. * @typedef {object} GeneratedSourceInfo
  8. * @property {number=} generatedLine generated line
  9. * @property {number=} generatedColumn generated column
  10. * @property {string=} source source
  11. */
  12. /**
  13. * @param {string | undefined} source source
  14. * @returns {GeneratedSourceInfo} source info
  15. */
  16. const getGeneratedSourceInfo = (source) => {
  17. if (source === undefined) {
  18. return {};
  19. }
  20. const lastLineStart = source.lastIndexOf("\n");
  21. if (lastLineStart === -1) {
  22. return {
  23. generatedLine: 1,
  24. generatedColumn: source.length,
  25. source,
  26. };
  27. }
  28. // Use native indexOf to scan for newlines instead of charCodeAt loops.
  29. // This is significantly faster on large sources since indexOf uses
  30. // vectorized/native string scanning.
  31. let generatedLine = 2;
  32. let idx = source.indexOf("\n");
  33. while (idx !== -1 && idx < lastLineStart) {
  34. generatedLine++;
  35. idx = source.indexOf("\n", idx + 1);
  36. }
  37. return {
  38. generatedLine,
  39. generatedColumn: source.length - lastLineStart - 1,
  40. source,
  41. };
  42. };
  43. module.exports = getGeneratedSourceInfo;