-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_lexer.js
More file actions
59 lines (52 loc) · 1.81 KB
/
Copy pathtest_lexer.js
File metadata and controls
59 lines (52 loc) · 1.81 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
const code = `import { Signal } from 'mita-dom';
const nombreUsuario = new Signal("Invitado");
// Leer el valor
console.log(nombreUsuario.value);
nombreUsuario.set("Victor Code");`;
function _escaparHTML(str) {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function _resaltarSintaxis(codigo, lenguaje) {
let code = _escaparHTML(codigo);
const tokens = [
{ type: 'string', regex: /^(?:".*?"|'.*?'|`[\s\S]*?`)/ },
{ type: 'comment', regex: /^(?:\/\/.*|\/\*[\s\S]*?\*\/)/ },
{ type: 'control-keyword', regex: /^(?:if|else|for|while|return|try|catch|switch|case|break|continue|await|async)\b/ },
{ type: 'keyword', regex: /^(?:import|export|class|extends|constructor|super|this|new|const|let|var|function|typeof|default|from)\b/ },
{ type: 'boolean', regex: /^(?:true|false|null|undefined)\b/ },
{ type: 'function', regex: /^[a-zA-Z_$][a-zA-Z0-9_$]*(?=\s*\()/ },
{ type: 'number', regex: /^\b\d+(\.\d+)?\b/ },
{ type: 'operator', regex: /^(?:\+|-|\*|\/|%|={1,3}|!|&|<|>|\|{1,2})/ },
{ type: 'text', regex: /^[\s\S]/ }
];
let html = '';
let current = code;
while (current.length > 0) {
let matched = false;
for (const t of tokens) {
const match = current.match(t.regex);
if (match) {
if (t.type === 'text') {
html += match[0];
} else {
html += `<span class="token ${t.type}">${match[0]}</span>`;
}
current = current.substring(match[0].length);
matched = true;
break;
}
}
if (!matched) {
// Fallback infinito
html += current[0];
current = current.substring(1);
}
}
return html;
}
console.log(_resaltarSintaxis(code, 'javascript'));