-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathsyntaxer.js
More file actions
64 lines (57 loc) · 1.26 KB
/
syntaxer.js
File metadata and controls
64 lines (57 loc) · 1.26 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
const { StartTagToken, EndTagToken } = require('./lexer')
class HTMLDocument {
constructor () {
this.isDocument = true
this.childNodes = []
}
}
class Node {}
class Element extends Node {
constructor (token) {
super(token)
for (const key in token) {
this[key] = token[key]
}
this.childNodes = []
}
[Symbol.toStringTag] () {
return `Element<${this.name}>`
}
}
class Text extends Node {
constructor (value) {
super(value)
this.value = value || ''
}
}
function HTMLSyntaticalParser () {
const stack = [new HTMLDocument]
this.receiveInput = function (token) {
if (typeof token === 'string') {
if (getTop(stack) instanceof Text) {
getTop(stack).value += token
} else {
let t = new Text(token)
getTop(stack).childNodes.push(t)
stack.push(t)
}
} else if (getTop(stack) instanceof Text) {
stack.pop()
}
if (token instanceof StartTagToken) {
let e = new Element(token)
getTop(stack).childNodes.push(e)
return stack.push(e)
}
if (token instanceof EndTagToken) {
return stack.pop()
}
}
this.getOutput = () => stack[0]
}
function getTop (stack) {
return stack[stack.length - 1]
}
module.exports = {
HTMLSyntaticalParser
}