UNPKG

820 BJavaScriptView Raw
1export default function indentString(string, count = 1, options = {}) {
2 const {
3 indent = ' ',
4 includeEmptyLines = false
5 } = options;
6
7 if (typeof string !== 'string') {
8 throw new TypeError(
9 `Expected \`input\` to be a \`string\`, got \`${typeof string}\``
10 );
11 }
12
13 if (typeof count !== 'number') {
14 throw new TypeError(
15 `Expected \`count\` to be a \`number\`, got \`${typeof count}\``
16 );
17 }
18
19 if (count < 0) {
20 throw new RangeError(
21 `Expected \`count\` to be at least 0, got \`${count}\``
22 );
23 }
24
25 if (typeof indent !== 'string') {
26 throw new TypeError(
27 `Expected \`options.indent\` to be a \`string\`, got \`${typeof indent}\``
28 );
29 }
30
31 if (count === 0) {
32 return string;
33 }
34
35 const regex = includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
36
37 return string.replace(regex, indent.repeat(count));
38}