@wordpress/block-library
Version:
Block library for the WordPress editor.
8 lines (7 loc) • 2.33 kB
Source Map (JSON)
{
"version": 3,
"sources": ["../../src/comment-template/util.js"],
"sourcesContent": ["/**\n *\n * This function converts a flat list of comment objects with a `parent` property\n * to a nested list of comment objects with a `children` property. The `children`\n * property is itself a list of comment objects.\n *\n * @example\n * ```\n * const comments = [\n * \t{ id: 1, parent: 0 },\n * \t{ id: 2, parent: 1 },\n * \t{ id: 3, parent: 2 },\n * \t{ id: 4, parent: 1 },\n * ];\n * expect( convertToTree( comments ) ).toEqual( [\n * \t{\n * \t\tcommentId: 1,\n * \t\tchildren: [\n * \t\t\t{ commentId: 2, children: [ { commentId: 3, children: [] } ] },\n * \t\t\t{ commentId: 4, children: [] },\n * \t\t],\n * \t},\n * ] );\n * ```\n * @typedef {{id: number, parent: number}} Comment\n * @param {Comment[]} data - List of comment objects.\n *\n * @return {Object[]} Nested list of comment objects with a `children` property.\n */\nexport const convertToTree = ( data ) => {\n\tconst table = {};\n\n\tif ( ! data ) {\n\t\treturn [];\n\t}\n\n\t// First create a hash table of { [id]: { ...comment, children: [] }}\n\tdata.forEach( ( item ) => {\n\t\ttable[ item.id ] = { commentId: item.id, children: [] };\n\t} );\n\n\tconst tree = [];\n\n\t// Iterate over the original comments again\n\tdata.forEach( ( item ) => {\n\t\tif ( item.parent ) {\n\t\t\t// If the comment has a \"parent\", then find that parent in the table that\n\t\t\t// we have created above and push the current comment to the array of its\n\t\t\t// children.\n\t\t\ttable[ item.parent ]?.children.push( table[ item.id ] );\n\t\t} else {\n\t\t\t// Otherwise, if the comment has no parent (also works if parent is 0)\n\t\t\t// that means that it's a top-level comment so we can find it in the table\n\t\t\t// and push it to the final tree.\n\t\t\ttree.push( table[ item.id ] );\n\t\t}\n\t} );\n\treturn tree;\n};\n"],
"mappings": ";AA6BO,IAAM,gBAAgB,CAAE,SAAU;AACxC,QAAM,QAAQ,CAAC;AAEf,MAAK,CAAE,MAAO;AACb,WAAO,CAAC;AAAA,EACT;AAGA,OAAK,QAAS,CAAE,SAAU;AACzB,UAAO,KAAK,EAAG,IAAI,EAAE,WAAW,KAAK,IAAI,UAAU,CAAC,EAAE;AAAA,EACvD,CAAE;AAEF,QAAM,OAAO,CAAC;AAGd,OAAK,QAAS,CAAE,SAAU;AACzB,QAAK,KAAK,QAAS;AAIlB,YAAO,KAAK,MAAO,GAAG,SAAS,KAAM,MAAO,KAAK,EAAG,CAAE;AAAA,IACvD,OAAO;AAIN,WAAK,KAAM,MAAO,KAAK,EAAG,CAAE;AAAA,IAC7B;AAAA,EACD,CAAE;AACF,SAAO;AACR;",
"names": []
}