No Description

index.js 1.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*!
  2. * align-text <https://github.com/jonschlinkert/align-text>
  3. *
  4. * Copyright (c) 2015, Jon Schlinkert.
  5. * Licensed under the MIT License.
  6. */
  7. 'use strict';
  8. var typeOf = require('kind-of');
  9. var repeat = require('repeat-string');
  10. var longest = require('longest');
  11. module.exports = function alignText(val, fn) {
  12. var lines, type = typeOf(val);
  13. if (type === 'array') {
  14. lines = val;
  15. } else if (type === 'string') {
  16. lines = val.split(/(?:\r\n|\n)/);
  17. } else {
  18. throw new TypeError('align-text expects a string or array.');
  19. }
  20. var fnType = typeOf(fn);
  21. var len = lines.length;
  22. var max = longest(lines);
  23. var res = [], i = 0;
  24. while (len--) {
  25. var line = String(lines[i++]);
  26. var diff;
  27. if (fnType === 'function') {
  28. diff = fn(line.length, max.length, line, lines, i);
  29. } else if (fnType === 'number') {
  30. diff = fn;
  31. } else {
  32. diff = max.length - line.length;
  33. }
  34. if (typeOf(diff) === 'number') {
  35. res.push(repeat(' ', diff) + line);
  36. } else if (typeOf(diff) === 'object') {
  37. var result = repeat(diff.character || ' ', diff.indent || 0);
  38. res.push((diff.prefix || '') + result + line);
  39. }
  40. }
  41. if (type === 'array') return res;
  42. return res.join('\n');
  43. };