-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.js
More file actions
86 lines (68 loc) · 1.83 KB
/
index.js
File metadata and controls
86 lines (68 loc) · 1.83 KB
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
module.exports = createElement
createElement.openingTag = openingTag
createElement.closingTag = closingTag
createElement.attributes = createAttributes
var selfClosingTags = createElement.selfClosingTags = {
meta: true,
img: true,
link: true,
input: true,
source: true,
area: true,
base: true,
col: true,
br: true,
hr: true
}
/*
tagName [string]
attributes [object] (optional)
block [string || function] (optional)
*/
function createElement(tagName, attributes, block) {
if (~['function', 'string'].indexOf(typeof attributes)) {
block = attributes
attributes = null
}
return openingTag(tagName, attributes) +
(block ? (typeof block === 'function' ? block.call(this, '') : block) : '') +
(block || !selfClosingTags[tagName] ? closingTag(tagName) : '')
}
function openingTag(tagName, attributes) {
return '<' + tagName +
(attributes ? createAttributes(attributes) : '') +
'>'
}
function closingTag(tagName) {
return '</' + tagName + '>'
}
/*
attributes [object]
[string] : [string || array of strings || object of booleans || boolean]
result will have a leading space
*/
function createAttributes(attributes) {
var buf = ''
Object.keys(attributes).forEach(function (attribute) {
var value = attributes[attribute]
if (!truthyEnough(value)) return;
value = Array.isArray(value) ? validValues(value)
: Object(value) === value ? validKeys(value)
: value
if (!truthyEnough(value)) return;
buf += ' ' + attribute
if (value !== true) buf += '="' + value + '"';
})
return buf
}
function truthyEnough (value) {
return value || value === 0 || value === '';
}
function validValues(array) {
return array.filter(Boolean).join(' ')
}
function validKeys(object) {
return Object.keys(object).filter(function (key) {
return object[key]
}).join(' ')
}