UNPKG

1.24 kBJavaScriptView Raw
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
8'use strict';
9
10var typeOf = require('kind-of');
11var repeat = require('repeat-string');
12var longest = require('longest');
13
14module.exports = function alignText(val, fn) {
15 var lines, type = typeOf(val);
16
17 if (type === 'array') {
18 lines = val;
19 } else if (type === 'string') {
20 lines = val.split(/(?:\r\n|\n)/);
21 } else {
22 throw new TypeError('align-text expects a string or array.');
23 }
24
25 var fnType = typeOf(fn);
26 var len = lines.length;
27 var max = longest(lines);
28 var res = [], i = 0;
29
30 while (len--) {
31 var line = String(lines[i++]);
32 var diff;
33
34 if (fnType === 'function') {
35 diff = fn(line.length, max.length, line, lines, i);
36 } else if (fnType === 'number') {
37 diff = fn;
38 } else {
39 diff = max.length - line.length;
40 }
41
42 if (typeOf(diff) === 'number') {
43 res.push(repeat(' ', diff) + line);
44 } else if (typeOf(diff) === 'object') {
45 var result = repeat(diff.character || ' ', diff.indent || 0);
46 res.push((diff.prefix || '') + result + line);
47 }
48 }
49
50 if (type === 'array') return res;
51 return res.join('\n');
52};