Collect children

Benchmark created on


Preparation HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.js"></script>

Setup

const depth = 3;
const width = 2

const createItem = (parentIds) => ({ id: _.uniqueId(), parentIds });

const list = [createItem()]

const populateNode = (node, d) => {
  const children = []
  for (let i = 0; i < width; i++) {
  	children.push(createItem([node.id]))
  }	
  list.push(...children)
  if (d < depth) children.forEach(c => populateNode(c, d + 1))
}

populateNode(list[0], 0)

Test runner

Ready to run.

Testing in
TestOps/sec
getScripts
const getScriptsList = (
  parentScriptId,
  scripts,
  acc = []
) => {
  const scriptsFromParent = scripts.filter(script =>
    script.parentIds?.includes(parentScriptId),
  )

  if (scriptsFromParent.length) {
    const filteredScripts = _.differenceBy(scriptsFromParent, acc, 'id')

    if (filteredScripts.length) {
      const listOfScripts = filteredScripts.flatMap(script =>
        getScriptsList(script.id, scripts, [...acc, script]),
      )
      return listOfScripts
    }
  }

  return acc.flat()
}

getScriptsList(list[0].id, list.slice(1))
ready
collectChildren
const collectChildren = (root, scripts) => {
  const children = scripts.filter(s => s.parentIds?.includes(root.id)) || []
   return _.uniqBy(
    [
      root,
      ...children,
      ...children.flatMap(c => collectChildren(c, scripts)),
    ],
    'id',
  )
}

collectChildren(list[0], list.slice(1))

ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.