UNPKG

@wordpress/block-library

Version:
1 lines • 2.27 kB
{"version":3,"file":"util.mjs","names":[],"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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,iBAAkB,SAAU;CACxC,MAAM,QAAQ,CAAC;CAEf,IAAK,CAAE,MACN,OAAO,CAAC;CAIT,KAAK,SAAW,SAAU;EACzB,MAAO,KAAK,MAAO;GAAE,WAAW,KAAK;GAAI,UAAU,CAAC;EAAE;CACvD,CAAE;CAEF,MAAM,OAAO,CAAC;CAGd,KAAK,SAAW,SAAU;EACzB,IAAK,KAAK,QAIT,MAAO,KAAK,OAAQ,EAAE,SAAS,KAAM,MAAO,KAAK,GAAK;OAKtD,KAAK,KAAM,MAAO,KAAK,GAAK;CAE9B,CAAE;CACF,OAAO;AACR"}