-
Notifications
You must be signed in to change notification settings - Fork 1
/
getHtmlHeadersMarkup.ts
71 lines (61 loc) · 1.45 KB
/
getHtmlHeadersMarkup.ts
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
import {
IHtmlHeader
} from './types';
const attributeNamesOrder = [
'name',
'content',
'rel',
'type',
'sizes',
'media',
'href'
];
/**
* Get order index of attribute name.
* @param attributeName - Target attribute name.
* @return Index.
*/
function getAttributeOrder(attributeName: string) {
const index = attributeNamesOrder.indexOf(attributeName);
return index === -1
? attributeNamesOrder.length
: index;
}
/**
* Comparator function to sort attributes entries.
* @param a - Left attribute entry.
* @param b - Right attribute entry.
* @return Result of comparation.
*/
function comparator([a]: [string, any], [b]: [string, any]) {
return getAttributeOrder(a) - getAttributeOrder(b);
}
/**
* Make attribute string from entry.
* @param entry - Entry with attribute name and value.
* @return Attribute string.
*/
function entryToString([key, value]: [string, string]) {
return `${key}="${String(value)}"`;
}
/**
* Get HTML-markup from objects.
* @param header - Object or array of objects with header info.
* @return HTML-markup.
*/
export function getHtmlHeadersMarkup(header: IHtmlHeader|IHtmlHeader[]): string {
if (Array.isArray(header)) {
return header.map(getHtmlHeadersMarkup).join('\n');
}
const {
tagName,
...attributes
} = header;
const attributesString = Object
.entries(attributes)
.sort(comparator)
.map(entryToString)
.join(' ');
const markup = `<${tagName} ${attributesString}>`;
return markup;
}