index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*!
  2. * condense-newlines <https://github.com/jonschlinkert/condense-newlines>
  3. *
  4. * Copyright (c) 2014 Jon Schlinkert, contributors.
  5. * Licensed under the MIT License
  6. */
  7. 'use strict';
  8. var isWhitespace = require('is-whitespace');
  9. var extend = require('extend-shallow');
  10. var typeOf = require('kind-of');
  11. module.exports = function(str, options) {
  12. var opts = extend({}, options);
  13. var sep = opts.sep || '\n\n';
  14. var min = opts.min;
  15. var re;
  16. if (typeof min === 'number' && min !== 2) {
  17. re = new RegExp('(\\r\\n|\\n|\\u2424) {' + min + ',}');
  18. }
  19. if (typeof re === 'undefined') {
  20. re = opts.regex || /(\r\n|\n|\u2424){2,}/g;
  21. }
  22. // if a line is 100% whitespace it will be trimmed, so that
  23. // later we can condense newlines correctly
  24. if (opts.keepWhitespace !== true) {
  25. str = str.split('\n').map(function(line) {
  26. return isWhitespace(line) ? line.trim() : line;
  27. }).join('\n');
  28. }
  29. str = trailingNewline(str, opts);
  30. return str.replace(re, sep);
  31. };
  32. function trailingNewline(str, options) {
  33. var val = options.trailingNewline;
  34. if (val === false) {
  35. return str;
  36. }
  37. switch (typeOf(val)) {
  38. case 'string':
  39. str = str.replace(/\s+$/, options.trailingNewline);
  40. break;
  41. case 'function':
  42. str = options.trailingNewline(str);
  43. break;
  44. case 'undefined':
  45. case 'boolean':
  46. default: {
  47. str = str.replace(/\s+$/, '\n');
  48. break;
  49. }
  50. }
  51. return str;
  52. }