-
Notifications
You must be signed in to change notification settings - Fork 3
/
stringify.js
91 lines (74 loc) · 1.75 KB
/
stringify.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
'use strict';
const isObject = o => o && Object.prototype.toString.call(o) === '[object Object]';
function indenter (indentation) {
if (!(indentation > 0)) {
return txt => txt;
}
var space = ' '.repeat(indentation);
return txt => {
if (typeof txt !== 'string') {
return txt;
}
const arr = txt.split('\n');
if (arr.length === 1) {
return space + txt;
}
return arr
.map(e => (e.trim() === '') ? e : space + e)
.join('\n');
};
}
const clean = txt => txt
.split('\n')
.filter(e => e.trim() !== '')
.join('\n');
function stringify (a, indentation) {
const cr = (indentation > 0) ? '\n' : '';
const indent = indenter(indentation);
function rec(a) {
let body = '';
let isFlat = true;
let res;
const isEmpty = a.some((e, i, arr) => {
if (i === 0) {
res = '<' + e;
return (arr.length === 1);
}
if (i === 1) {
if (isObject(e)) {
Object.keys(e).map(key => {
let val = e[key];
if (Array.isArray(val)) {
val = val.join(' ');
}
res += ' ' + key + '="' + val + '"';
});
if (arr.length === 2) {
return true;
}
res += '>';
return;
}
res += '>';
}
switch (typeof e) {
case 'string':
case 'number':
case 'boolean':
case 'undefined':
body += e + cr;
return;
}
isFlat = false;
body += rec(e);
});
if (isEmpty) {
return res + '/>' + cr; // short form
}
return isFlat
? res + clean(body) + '</' + a[0] + '>' + cr
: res + cr + indent(body) + '</' + a[0] + '>' + cr;
}
return rec(a);
}
module.exports = stringify;