Skip to content

Commit

Permalink
Refactor to simplify code
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed Jul 15, 2021
1 parent 75c8293 commit 2323d38
Showing 1 changed file with 23 additions and 62 deletions.
85 changes: 23 additions & 62 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,63 +30,6 @@ export const unified = base().freeze()

const own = {}.hasOwnProperty

// Process pipeline.
const pipeline = trough()
.use(pipelineParse)
.use(pipelineRun)
.use(pipelineStringify)

/**
* @param {Processor} p
* @param {Context} ctx
*/
function pipelineParse(p, ctx) {
ctx.tree = p.parse(ctx.file)
}

/**
* @param {Processor} p
* @param {Context} ctx
* @param {(error?: Error) => void} next
*/
function pipelineRun(p, ctx, next) {
p.run(ctx.tree, ctx.file, done)

/**
* @param {Error|null} [error]
* @param {Node|undefined} [tree]
* @param {VFile|undefined} [file]
*/
function done(error, tree, file) {
if (error) {
next(error)
} else {
// @ts-expect-error: either `error` or `tree` and `value` is given.
ctx.tree = tree
// @ts-expect-error: either `error` or `tree` and `value` is given.
ctx.file = file
next()
}
}
}

/**
* @param {Processor} p
* @param {Context} ctx
*/
function pipelineStringify(p, ctx) {
/** @type {unknown} */
const result = p.stringify(ctx.tree, ctx.file)

if (result === undefined || result === null) {
// Empty.
} else if (looksLikeAVFileValue(result)) {
ctx.file.value = result
} else {
ctx.file.result = result
}
}

// Function to create the first processor.
/**
* @returns {Processor}
Expand Down Expand Up @@ -441,20 +384,38 @@ function base() {

/**
* @param {null|((file: VFile) => void)} resolve
* @param {(error: Error) => void} reject
* @param {(error?: Error|null|undefined) => void} reject
* @returns {void}
*/
function executor(resolve, reject) {
const file = vfile(doc)

pipeline.run(processor, {file}, done)
processor.run(processor.parse(file), file, (error, tree, file) => {
if (error || !tree || !file) {
done(error)
} else {
/** @type {unknown} */
const result = processor.stringify(tree, file)

if (result === undefined || result === null) {
// Empty.
} else if (looksLikeAVFileValue(result)) {
file.value = result
} else {
file.result = result
}

done(error, file)
}
})

/**
* @param {Error|null} error
* @param {Error|null|undefined} [error]
* @param {VFile|undefined} [file]
* @returns {void}
*/
function done(error) {
if (error) {
function done(error, file) {
if (error || !file) {
reject(error)
} else if (resolve) {
resolve(file)
Expand Down

0 comments on commit 2323d38

Please sign in to comment.