diff --git a/markdown.js b/markdown.js index 70c526a..e9e72a2 100644 --- a/markdown.js +++ b/markdown.js @@ -1,20 +1,3 @@ -const SymbolsToCheck = [Heading]; - -export const toHtml = (markdown) => { - const symbols = toSymbols(markdown); - - return `
${lineFeed.feed}
`; -}; - -const toSymbols = (markdown) => { - const lineFeed = new LineFeed(markdown); - const symbols = []; - - while (!lineFeed.isEmpty()) {} - - return symbols; -}; - class LineFeed { originalText = undefined; /** @@ -40,7 +23,7 @@ class LineFeed { /** * - * @returns {string|undefined} + * @returns {string} */ claim() { const line = this.feed.shift(); @@ -70,6 +53,14 @@ class Symbol { } class Heading extends Symbol { + /** + * @type {string} + */ + text = ""; + /** + * @type {number} + */ + level = 1; /** * * @param {string} line @@ -78,10 +69,74 @@ class Heading extends Symbol { static canParse(line) { return line.trim().startsWith("#"); } + + /** + * + * @param {LineFeed} lineFeed + * @returns {Symbol} + */ static create(lineFeed) { - throw new Error("Not implemented"); + const instance = new Heading(); + const line = lineFeed.claim(); + instance.text = line.replaceAll("#", "").trim(); + instance.level = line.split("").reduce((aggregate, current) => { + return current === "#" ? aggregate + 1 : aggregate; + }, 0); + return instance; } + render() { - return `

${Symbol.text}

`; + return `${this.text}`; } } + +class CatchAll extends Symbol { + /** + * @type {string} + */ + text = ""; + /** + * + * @param {string} line + * @returns {boolean} + */ + static canParse(line) { + return true; + } + + /** + * + * @param {LineFeed} lineFeed + * @returns {Symbol} + */ + static create(lineFeed) { + const instance = new CatchAll(); + instance.text = lineFeed.claim(); + return instance; + } + render() { + return `

${this.text}

`; + } +} + +const Factories = [Heading, CatchAll]; + +export const toHtml = (markdown) => { + const symbols = toSymbols(markdown); + const html = symbols.map((s) => s.render()).join(""); + return `
${html}
`; +}; + +const toSymbols = (markdown) => { + const lineFeed = new LineFeed(markdown); + const symbols = []; + + while (!lineFeed.isEmpty()) { + const line = lineFeed.peek(); + const factory = Factories.find((factory) => factory.canParse(line)); + const symbol = factory.create(lineFeed); + symbols.push(symbol); + } + + return symbols; +};