Skip to content

Instantly share code, notes, and snippets.

@danielyaa5
Created January 29, 2020 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielyaa5/f944ca7ea0fd9d8cd1868b13b18f0410 to your computer and use it in GitHub Desktop.
Save danielyaa5/f944ca7ea0fd9d8cd1868b13b18f0410 to your computer and use it in GitHub Desktop.
const getTag = (text, [lastParsedTag, lastParsedText] = [null, null]) => {
if (text.length === 0) return null;
const listItem = text[0] === '-';
if (listItem) return 'li';
const hashes = text.match(/^#+/);
if (hashes) return `h${Math.min(6, hashes[0].length)}`;
if (lastParsedTag === 'p' || lastParsedTag === 'li') return 'continued';
return 'p';
};
const clean = (text, tag) => {
if (tag && tag[0] === 'h') return text.substring(tag[1]).trim();
return text.replace(/^-\s*/, '');
}
const isContinuedTag = tag => tag.includes('continued-');
const wrapHtml = body => `<html>\n<body>\n${body}</body>\n</html>`;
const toHtml = parsedLines => parsedLines.reduce((acc, [currTag, currText], i) => {
const [lastTag, lastText] = i > 0 ? parsedLines[i - 1] : [null, null];
if (currTag === 'li' && lastTag !== 'li') {
acc += '<ul>\n'
}
if (currTag) {
acc += `<${currTag}>${clean(currText, currTag)}</${currTag}>\n`;
}
if (currTag === null && lastTag === 'li') {
acc += '</ul>\n'
}
return acc;
}, '');
const parse = md => md.split('\n').reduce((acc, line, i, src) => {
const text = line.trim();
const lastParsedLine = i > 0 ? acc[acc.length - 1] : [null, null];
const [lastParsedTag, lastParsedText] = lastParsedLine;
const lineTag = getTag(text, lastParsedLine);
if (lineTag === 'continued') {
lastParsedLine[1] = `${lastParsedText} ${text}`;
} else if (lineTag === null && lastParsedTag !== null) {
acc.push([null, null]);
} else {
acc.push([lineTag, text]);
}
const isLastLine = i === src.length - 1;
if (isLastLine) return wrapHtml(toHtml(acc));
return acc;
}, []);
const test = `
# hello, This is Markdown Live Preview
## what is Markdown?
## usage
## markdown quick reference
# headers
- hey
- adofasdkfjadsjfasdklflsdajf
jfasdkflsajdfklsadjfasdf
- fasdfasd
hello im a paragraph
on mulitple lines
heres a new paragraph
`;
console.log(parse(test));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment