1 /**
2  * Text manipulation
3  *
4  * Authors: Tristan Brice Velloza Kildaire
5  */
6 module niknaks.text;
7 
8 import std.string : join, format, split;
9 
10 version(unittest)
11 {
12     import std.stdio;
13 }
14 
15 /** 
16  * Generates a string containing
17  * the provided pattern repeated
18  * by the given number of times
19  *
20  * Params:
21  *   count = the number of times
22  * to repeat the pattern
23  *   pattern = the pattern itself
24  * Returns: the repeated pattern
25  */
26 public string genX(size_t count, string pattern)
27 {
28     string strOut;
29     for(ubyte i = 0; i < count; i++)
30     {
31         strOut ~= pattern;
32     }
33     return strOut;
34 }
35 
36 /**
37  * Tests the generation of a pattern
38  */
39 unittest
40 {
41     string pattern = "YOLO";
42     size_t count = 2;
43 
44     string output = genX(count, pattern);
45     assert(output == "YOLOYOLO");
46 }
47 
48 /** 
49  * Generates a string containing
50  * the number of tabs specified
51  *
52  * Params:
53  *   count = the number of tabs
54  * Returns: the tabbed string
55  */
56 public string genTabs(size_t count)
57 {
58     return genX(count, "\t");
59 }
60 
61 /**
62  * Tests `genTabs(size_t)`
63  */
64 unittest
65 {
66     size_t count = 2;
67 
68     string output = genTabs(count);
69     assert(output == "\t\t");
70 }
71 
72 /** 
73  * Pads the left-hand margin of a multi-line
74  * string with the given text
75  *
76  * Params:
77  *   bodyText = the text to pad
78  *   withText = the padding text
79  * Returns: the padded text
80  */
81 public string padLeft(string bodyText, string withText)
82 {
83     string[] lines_out;
84     string[] lines_in = split(bodyText, "\n");
85     foreach(string l; lines_in)
86     {
87         lines_out ~= format("%s%s", withText, l);
88     }
89 
90     return join(lines_out, "\n");
91 }
92 
93 
94 /**
95  * Tests out the left-padding of text
96  * with a custom text segment
97  */
98 unittest
99 {
100     string input = `Hello
101 World
102 `;
103 
104     string output = padLeft(input, "%");
105 
106     string[] output_segments = output.split("\n");
107     writeln(output_segments);
108     assert(output_segments[0] == "%Hello");
109     assert(output_segments[1] == "%World");
110     assert(output_segments[2] == "%");
111 }