@rnaga/wp-node
Version:
👉 **[View Full Documentation at rnaga.github.io/wp-node →](https://rnaga.github.io/wp-node/)**
79 lines (78 loc) • 2.19 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.map = exports.flat = exports.terms = exports.posts = exports.comments = void 0;
const to = (table, items) => {
const flat = items.map((item) => ({
...item,
depth: 0,
children: [],
}));
const hierarchy = [];
outerLoop: for (const item of flat) {
const parentId = table == "terms"
? item.parent
: table == "comments"
? item.comment_parent
: item.post_parent;
if (0 >= parentId) {
hierarchy.push(item);
continue;
}
for (const parent of flat) {
const parentItemId = table == "terms"
? parent.term_id
: table == "comments"
? parent.comment_ID
: parent.ID;
if (parentId == parentItemId) {
item.depth = parent.depth + 1;
parent.children.push(item);
continue outerLoop;
}
}
// If no parent is found in the entire flat array, add the item to hierarchy
hierarchy.push(item);
}
return hierarchy;
};
const comments = (comments) => {
return to("comments", comments);
};
exports.comments = comments;
const posts = (posts) => {
return to("posts", posts);
};
exports.posts = posts;
const terms = (terms) => {
return to("terms", terms);
};
exports.terms = terms;
const flat = (table, items) => {
const r = [];
function innerFn(hierarchy) {
for (const item of hierarchy) {
r.push({ ...item, depth: item.depth });
if (item.children) {
innerFn(item.children);
}
}
}
innerFn(to(table, items));
return r;
};
exports.flat = flat;
const map = (table, items, cb) => {
const r = [];
let index = 0;
function innerFn(hierarchy) {
for (const item of hierarchy) {
r.push(cb(item, index++));
if (item.children) {
innerFn(item.children);
}
}
}
innerFn(to(table, items));
return r;
};
exports.map = map;