Advertisement
Guest User

Untitled

a guest
May 27th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. /**
  2. * Example module to get info about a multi-line string,
  3. * written as a node.js module.
  4. *
  5. * Takes a multiline string, and returns an Object:
  6. *
  7. * "here is a line of text"
  8. *
  9. * {
  10. * lines: [
  11. * {
  12. * line: "here is a line of text",
  13. * count: 17
  14. * },
  15. * {
  16. * line: "here is the 2nd line of text",
  17. * count: 17
  18. * },
  19. *
  20. * count: 17
  21. * }
  22.  
  23. /**
  24. * Split the given string into lines, taking into
  25. * account Windows (\r\n) vs. Unix (\n) line endings.
  26. */
  27. const splitIntoLines = text => text.split(/\r?\n/);
  28.  
  29. /*
  30. * Count the number of non-whitespace (space, tab, etc)
  31. * characters in the given string, returning the count
  32. * "here is a line of text" -> 17
  33. */
  34. const countNonWhitespace = text => text.replace(/\s+/g, '').length;
  35.  
  36. /**
  37. * Process a list of lines (Array of Strings) into an
  38. * Array of Objects, where each Object has info about
  39. * the given line:
  40. *
  41. * - The `line` itself
  42. * - The `count` of non-whitespace characters in the line
  43. * - The `number` of the line in the string, starting at 1
  44. */
  45. const processLines = list =>
  46. list.map((element, index) => {
  47. return {
  48. line: element,
  49. count: countNonWhitespace(element),
  50. number: index + 1
  51. };
  52. });
  53.  
  54. const getTotalCharacters = lines =>
  55. lines.reduce((total, element) => total + element.count, 0);
  56.  
  57. /**
  58. * Main public entry point to the module. Take
  59. * the given multi-line string, and produce an Object
  60. * with info about each line, as well as a total
  61. * character count for non-whitespace characters.
  62. */
  63. function processText(text) {
  64. const lines = processLines(splitIntoLines(text));
  65.  
  66. return {
  67. lines,
  68. total: getTotalCharacters(lines)
  69. };
  70. }
  71.  
  72. /**
  73. * Expose the `processText` function on the module's `exports`
  74. * Object, making it accessible to callers. All other functions
  75. * will remain "hidden" within this module.
  76. */
  77. exports.processText = processText;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement