From 8615f15cf346e497865496ab2035b6e08e21d036 Mon Sep 17 00:00:00 2001 From: Sukka Date: Mon, 17 Feb 2020 17:35:56 +0800 Subject: [PATCH] refactor(toc_obj): simplify the code (#181) --- lib/toc_obj.js | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/lib/toc_obj.js b/lib/toc_obj.js index aca1b1a6..8abcfe0a 100644 --- a/lib/toc_obj.js +++ b/lib/toc_obj.js @@ -8,28 +8,26 @@ const parseHtml = html => { return handler.dom; }; -const getId = ele => { - const { id } = ele.attribs; - const { parent } = ele; - return id || (!parent ? null : getId(parent)); +const getId = ({ attribs, parent }) => { + return attribs.id || (!parent ? null : getId(parent)); }; function tocObj(str, options = {}) { - options = Object.assign({ + const { min_depth, max_depth } = Object.assign({ min_depth: 1, max_depth: 6 }, options); - const headingsSelector = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].slice(options.min_depth - 1, options.max_depth).join(','); + const headingsSelector = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].slice(min_depth - 1, max_depth); + const headings = DomUtils.find(({ tagName }) => headingsSelector.includes(tagName), parseHtml(str), true); + const headingsLen = headings.length; - const dom = parseHtml(str); - const headings = DomUtils.find(el => headingsSelector.includes(el.tagName), dom, true); + if (!headingsLen) return []; const result = []; - if (!headings.length) return result; - - for (const el of headings) { + for (let i = 0; i < headingsLen; i++) { + const el = headings[i]; const level = +el.name[1]; const id = getId(el); const text = escapeHTML(DomUtils.getText(el));