splitIntoLines.js 660 B

123456789101112131415161718192021222324252627282930313233
  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. const cc = str.charCodeAt(i);
  16. // 10 is "\n".charCodeAt(0)
  17. if (cc === 10) {
  18. results.push("\n");
  19. i++;
  20. } else {
  21. let j = i + 1;
  22. // 10 is "\n".charCodeAt(0)
  23. while (j < len && str.charCodeAt(j) !== 10) j++;
  24. results.push(str.slice(i, j + 1));
  25. i = j + 1;
  26. }
  27. }
  28. return results;
  29. };
  30. module.exports = splitIntoLines;