@wordpress/block-library
Version:
Block library for the WordPress editor.
49 lines (48 loc) • 1.23 kB
JavaScript
// packages/block-library/src/comment-template/util.js
/**
*
* This function converts a flat list of comment objects with a `parent` property
* to a nested list of comment objects with a `children` property. The `children`
* property is itself a list of comment objects.
*
* @example
* ```
* const comments = [
* { id: 1, parent: 0 },
* { id: 2, parent: 1 },
* { id: 3, parent: 2 },
* { id: 4, parent: 1 },
* ];
* expect( convertToTree( comments ) ).toEqual( [
* {
* commentId: 1,
* children: [
* { commentId: 2, children: [ { commentId: 3, children: [] } ] },
* { commentId: 4, children: [] },
* ],
* },
* ] );
* ```
* @typedef {{id: number, parent: number}} Comment
* @param {Comment[]} data - List of comment objects.
*
* @return {Object[]} Nested list of comment objects with a `children` property.
*/
const convertToTree = (data) => {
const table = {};
if (!data) return [];
data.forEach((item) => {
table[item.id] = {
commentId: item.id,
children: []
};
});
const tree = [];
data.forEach((item) => {
if (item.parent) table[item.parent]?.children.push(table[item.id]);
else tree.push(table[item.id]);
});
return tree;
};
export { convertToTree };
//# sourceMappingURL=util.mjs.map