fastparselite
Version:
Super simple & fast DSL parser for lightweight config-like data using custom syntax.
48 lines (41 loc) • 1.07 kB
JavaScript
function fastParseLite(text) {
const lines = text.split('\n').map(l => l.trim()).filter(l => l.length && !l.startsWith("//") && !l.startsWith("#"));
const stack = [{}];
let current = stack[0];
for (let line of lines) {
if (line.endsWith('{')) {
const key = line.slice(0, -1).trim();
const newObj = {};
current[key] = newObj;
stack.push(current);
current = newObj;
} else if (line === '}') {
current = stack.pop();
} else {
const [key, rawVal] = line.split('=').map(s => s.trim());
let val;
if (rawVal.startsWith('#')) {
val = Number(rawVal.slice(1));
} else if (rawVal.startsWith('!')) {
val = rawVal.slice(1) === 'true';
} else {
val = rawVal;
}
current[key] = val;
}
}
return stack[0];
}
const input = `
user{
name=Alice
age=#25
address{
city=New York
zip=#10001
}
active=!true
}
`;
const result = fastParseLite(input);
console.log(result.user.address.city); // New York