unist-utils-core
Version:
A collection of commonly used (albeit enhanced) algorithms based on unist and unist-util-xxx
77 lines • 3.34 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.visitAsync = void 0;
const tslib_1 = require("tslib");
const test_1 = require("./test");
const visit_1 = require("./visit");
/**
* The only difference between this function and @see visit, is that this function waits for the result returned by an AsyncVisitor to each node.
* NOTE: This is not the same as visiting all nodes in parallel. Each node is still visited in sequence, just not until the AsyncVisitor callback has completed it's visit of the previous node.
*/
function visitAsync(tree, tst, visitor, options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
if (typeof tst === 'function' && typeof visitor !== 'function') {
options = visitor;
visitor = tst;
tst = null;
}
let opts;
if (typeof options === 'boolean')
opts = { reverse: options };
else if (!options)
opts = {};
else
opts = options;
let is = (0, test_1.test)(tst);
// Visit a single node.
function one(node, index, parents) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
let result = [];
let subResult;
if (!tst || is(node, index, parents[parents.length - 1] || null)) {
let aResult = yield visitor(node, index, parents, opts.context);
result = (0, visit_1.visitorResultToTuple)(aResult);
if (result[0] === visit_1.EXIT)
return result;
}
if (result[0] !== visit_1.SKIP) {
let c = node.children;
if (c) {
let aSubResult = yield all(c, parents.concat(node));
subResult = (0, visit_1.visitorResultToTuple)(aSubResult);
return subResult[0] === visit_1.EXIT ? subResult : result;
}
}
return result;
});
}
// Visit children in `parent`.
function all(children, parents) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
let min = -1;
let step = opts.reverse ? -1 : 1;
let index = (opts.reverse ? children.length : min) + step;
let result;
if (opts.preTraverse)
yield visitor(undefined, visit_1.PreTraversalIndex, parents, opts.context);
while (index > min && index < children.length) {
result = yield one(children[index], index, parents);
if (result[0] === visit_1.EXIT)
break;
index = typeof result[1] === 'number' ? result[1] : index + step;
}
if (opts.postTraverse)
yield visitor(undefined, visit_1.PostTraversalIndex, parents, opts.context);
if (result)
return result;
});
}
// Begin
if (Array.isArray(tree))
yield all(tree, []);
else
yield one(tree, null, []);
});
}
exports.visitAsync = visitAsync;
//# sourceMappingURL=visit-async.js.map