Skip to content

Commit

Permalink
Optimize parsing complexity (fixes #80)
Browse files Browse the repository at this point in the history
Patch suggested by @stereobooster in #80, thank you. :)
  • Loading branch information
valeriangalliat committed Feb 6, 2021
1 parent 56b6034 commit 85afd1f
Showing 1 changed file with 32 additions and 27 deletions.
59 changes: 32 additions & 27 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,33 +59,38 @@ const anchor = (md, opts) => {
? isLevelSelectedArray(opts.level)
: isLevelSelectedNumber(opts.level)

tokens
.filter(token => token.type === 'heading_open')
.filter(token => isLevelSelected(Number(token.tag.substr(1))))
.forEach(token => {
// Aggregate the next token children text.
const title = tokens[tokens.indexOf(token) + 1]
.children
.filter(token => token.type === 'text' || token.type === 'code_inline')
.reduce((acc, t) => acc + t.content, '')

let slug = token.attrGet('id')

if (slug == null) {
slug = uniqueSlug(opts.slugify(title), slugs, false, opts.uniqueSlugStartIndex)
} else {
slug = uniqueSlug(slug, slugs, true, opts.uniqueSlugStartIndex)
}
token.attrSet('id', slug)

if (opts.permalink) {
opts.renderPermalink(slug, opts, state, tokens.indexOf(token))
}

if (opts.callback) {
opts.callback(token, { slug, title })
}
})
tokens.forEach((token, i) => {
if (token.type !== 'heading_open') {
return
}

if (!isLevelSelected(Number(token.tag.substr(1)))) {
return
}

// Aggregate the next token children text.
const title = tokens[i + 1]
.children
.filter(token => token.type === 'text' || token.type === 'code_inline')
.reduce((acc, t) => acc + t.content, '')

let slug = token.attrGet('id')

if (slug == null) {
slug = uniqueSlug(opts.slugify(title), slugs, false, opts.uniqueSlugStartIndex)
} else {
slug = uniqueSlug(slug, slugs, true, opts.uniqueSlugStartIndex)
}
token.attrSet('id', slug)

if (opts.permalink) {
opts.renderPermalink(slug, opts, state, tokens.indexOf(token))
}

if (opts.callback) {
opts.callback(token, { slug, title })
}
})
})
}

Expand Down

0 comments on commit 85afd1f

Please sign in to comment.