forked from codecrafters-io/build-your-own-x
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Model.js
70 lines (62 loc) · 1.61 KB
/
Model.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
const { JSDOM } = require('jsdom');
class Model {
constructor(html) {
this.html = html;
this.dom = new JSDOM(html);
}
getCategories() {
const { window } = this.dom;
return Array.from(window.document.querySelectorAll('h4')).map((elm) => ({
text: elm.textContent,
id: elm.id,
posts: this.getPosts(elm.id),
totalCount: this.getPosts(elm.id).length,
}));
}
getPosts(category) {
const { window } = this.dom;
return Array.from(
window.document.querySelectorAll(`#${category} + ul > li > a`)
).map((elm) => ({
title: elm.textContent,
language: elm.querySelector('strong')
? elm.querySelector('strong').textContent
: '',
href: elm.getAttribute('href'),
}));
}
getTableOfContent() {
const { window } = this.dom;
return Array.from(
window.document.querySelectorAll('h2#table-of-contents + ul > li a')
).map((elm) => ({
id: elm.getAttribute('href'),
title: elm.textContent,
}));
}
getLanguages() {
const { window } = this.dom;
return [
...new Set(
Array.from(window.document.querySelectorAll('a[href^="http"]'))
.map((elm) =>
elm.querySelector('strong')
? elm.querySelector('strong').textContent
: ''
)
.filter((lang) => !!lang)
),
];
}
serialize() {
return {
tableOfContent: this.getTableOfContent(),
categories: this.getCategories(),
languages: this.getLanguages(),
};
}
toJSON() {
return JSON.stringify(this.serialize());
}
}
module.exports = Model;