Skip to content

Commit

Permalink
refactor(toc_obj): simplify the code (#181)
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Feb 17, 2020
1 parent 7e084de commit 8615f15
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions lib/toc_obj.js
Expand Up @@ -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));
Expand Down

0 comments on commit 8615f15

Please sign in to comment.