splitIntoLines.js 728 B

12345678910111213141516171819202122232425262728293031323334
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /**
  7. * @param {string} str string
  8. * @returns {string[]} array of string separated by lines
  9. */
  10. const splitIntoLines = (str) => {
  11. const results = [];
  12. const len = str.length;
  13. let i = 0;
  14. while (i < len) {
  15. // indexOf is implemented natively and is significantly faster than
  16. // scanning char-by-char with charCodeAt for long lines.
  17. const n = str.indexOf("\n", i);
  18. if (n === -1) {
  19. results.push(i === 0 ? str : str.slice(i));
  20. break;
  21. }
  22. if (n === i) {
  23. results.push("\n");
  24. } else {
  25. results.push(str.slice(i, n + 1));
  26. }
  27. i = n + 1;
  28. }
  29. return results;
  30. };
  31. module.exports = splitIntoLines;