-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathextract.js
64 lines (49 loc) · 1.46 KB
/
extract.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
(function() {
var parse = function(template, root) {
root = root || document;
switch (Object.prototype.toString.call(template)) {
case '[object Array]':
return parseArray(template, root);
case '[object Object]':
return parseObject(template, root);
case '[object Function]':
return parseFunction(template, root);
case '[object String]':
return parseString(template, root);
}
};
var parseArray = function(template, root) {
// if the first item is null, use the current root and run all templates
if (template[0] == null) {
return template.slice(1).map(function(item) {
return parse(item, root);
});
}
var nodes = root.querySelectorAll(template[0]);
return Array.prototype.map.call(nodes, function(root) {
return parse(template[1], root);
});
};
var parseObject = function(template, root) {
var output = {};
for (var key in template) {
if (template.hasOwnProperty(key)) {
output[key] = parse(template[key], root);
}
}
return output;
};
var parseFunction = function(template, root) {
return template(root);
};
var parseString = function(template, root) {
// TODO: handle attribute at the end of a longer selector
if (template.substring(0, 1) == '@') {
return root.getAttribute(template.substring(1));
}
// TODO: traversing, e.g. parents
var node = root.querySelector(template);
return node ? node.textContent : null;
};
Extract = { parse: parse };
})();