From d262aae6b2151996a033aa00919663e66ea93273 Mon Sep 17 00:00:00 2001 From: wholteza Date: Sun, 17 Sep 2023 10:44:49 +0200 Subject: [PATCH] Link support --- markdown.js | 49 +++++++++++++++++++++++++++++----- notes/1-initial-commit/note.md | 1 + 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/markdown.js b/markdown.js index 2d5275c..46f6952 100644 --- a/markdown.js +++ b/markdown.js @@ -170,7 +170,6 @@ class OrderedListItem extends Symbol { return `
  • ${this.text} indentation level ${this.level}
  • `; } } - class Link extends Symbol { /** * @type {RegExp} @@ -205,8 +204,9 @@ class Link extends Symbol { static create(lineFeed) { const instance = new Link(); const line = lineFeed.claim().trim(); - const { text, link } = Link.textAndLinkRegExp.exec(line)?.groups ?? {}; - console.log("test:", text, link); + const [linkLine, rest] = extractTokenAndRest(Link.textAndLinkRegExp, line); + lineFeed.push(rest); + const { text, link } = Link.textAndLinkRegExp.exec(linkLine)?.groups ?? {}; instance.link = link ?? ""; instance.text = text ?? ""; return instance; @@ -459,13 +459,50 @@ class CatchAll extends Symbol { /** * - * @param {string} token + * @param {string|RexExp} token * @param {string} string * @returns {string[]} */ const splitStringAtToken = (token, string) => { - const index = string.indexOf(token); - return [string.slice(0, index), string.slice(index + token.length)]; + let index = 0; + let length = 0; + if (typeof token?.exec === "function") { + const exp = new RegExp(token); + const match = exp.exec(string); + index = match?.index ?? -1; + length = match?.[0].length ?? 0; + } else { + index = string.indexOf(token); + length = token.length; + } + + const splitTokenNotFound = index === -1; + if (splitTokenNotFound) return [string, ""]; + return [string.slice(0, index), string.slice(index + length)]; +}; + +/** + * + * @param {string|RexExp} token + * @param {string} string + * @returns {string[]} + */ +const extractTokenAndRest = (token, string) => { + let index = 0; + let length = 0; + if (typeof token?.exec === "function") { + const exp = new RegExp(token); + const match = exp.exec(string); + index = match?.index ?? -1; + length = match?.[0].length ?? 0; + } else { + index = string.indexOf(token); + length = token.length; + } + + const splitTokenNotFound = index === -1; + if (splitTokenNotFound) return [string, ""]; + return [string.slice(0, index + length), string.slice(index + length)]; }; /** diff --git a/notes/1-initial-commit/note.md b/notes/1-initial-commit/note.md index f7ea6dc..2399062 100644 --- a/notes/1-initial-commit/note.md +++ b/notes/1-initial-commit/note.md @@ -71,5 +71,6 @@ const y = () => { 1. ordered list item [link to the index](https://blog.zacke.dev) +[link to the index](https://blog.zacke.dev) with text after it ![alt-text](@asset/picture.png)