2
0
mirror of https://github.com/tenrok/BBob.git synced 2026-06-20 20:00:33 +03:00

feat(core): implement plugin api

This commit is contained in:
Nikolay Kostyurin
2018-07-30 22:52:48 +02:00
parent fdc05c0618
commit ee047e829b
5 changed files with 234 additions and 21 deletions
+40 -17
View File
@@ -1,21 +1,44 @@
class BBob {
constructor(plugins) {
this.plugins = plugins;
}
const parser = require('@bbob/parser');
const render = require('@bbob/html');
// parse() {
//
// }
//
// stringify() {
//
// }
//
// process(input) {
//
// }
const { iterate, match } = require('./utils');
function walk(cb) {
return iterate(this, cb);
}
module.exports = function bbob(...plugins) {
return new BBob(plugins);
module.exports = function bbob(plugs) {
const plugins = typeof plugs === 'function' ? [plugs] : plugs || [];
let options = {
skipParse: false,
};
return {
process(input, opts) {
options = opts || {};
const parseFn = options.parser || parser;
const renderFn = options.render || render;
let tree = options.skipParse
? input || []
: parseFn(input, options);
tree.walk = walk;
tree.match = match;
plugins.forEach((plugin) => {
tree = plugin(tree) || tree;
});
return {
get html() {
return renderFn(tree, tree.options);
},
tree,
messages: tree.messages,
};
},
};
};
+65
View File
@@ -0,0 +1,65 @@
/* eslint-disable no-plusplus */
const isObj = value => (typeof value === 'object');
const isBool = value => (typeof value === 'boolean');
function iterate(t, cb) {
const tree = t;
if (Array.isArray(tree)) {
for (let idx = 0; idx < tree.length; idx++) {
tree[idx] = iterate(cb(tree[idx]), cb);
}
} else if (tree && isObj(tree) && tree.content) {
iterate(tree.content, cb);
}
return tree;
}
function same(expected, actual) {
if (typeof expected !== typeof actual) {
return false;
}
if (!isObj(expected) || expected === null) {
return expected === actual;
}
if (Array.isArray(expected)) {
return expected.every(exp => [].some.call(actual, act => same(exp, act)));
}
return Object.keys(expected).every((key) => {
const ao = actual[key];
const eo = expected[key];
if (isObj(eo) && eo !== null && ao !== null) {
return same(eo, ao);
}
if (isBool(eo)) {
return eo !== (ao === null);
}
return ao === eo;
});
}
function match(expression, cb) {
return Array.isArray(expression)
? iterate(this, (node) => {
for (let idx = 0; idx < expression.length; idx++) {
if (same(expression[idx], node)) {
return cb(node);
}
}
return node;
})
: iterate(this, node => (same(expression, node) ? cb(node) : node));
}
module.exports = {
iterate,
match,
};