export
function flattenTree (items, spaces = 4, level = 0, parentNode = null, path = [], childrenKey = 'Children') {
  return items.reduce((acc, val, index) => acc.concat({
    ...val,
    path: [...path, childrenKey, index],
    parentNode,
    level,
    levelPrefix: String.fromCharCode(0xA0).repeat(level * spaces)
  }, ...flattenTree(val[childrenKey] || [], spaces, level + 1, val, [...path, childrenKey, index], childrenKey)), []);
}

export
function buildTree (items, idKey = 'id', parentKey = 'parentId', childrenKey = 'Children') {

  const buildNode = (items, id, parent) => items
    .filter(item => item[parentKey] === parent)
    .map(item => ({ ...item, [childrenKey]: buildNode(items, item[idKey], item[idKey], childrenKey) }));

  return buildNode(items, null, null, childrenKey);
}

export
function removeNode (tree, compareFn, childrenKey = 'Children') {
  return tree.reduce((acc, val) => {
    if (compareFn(val)) {
      return acc;
    }
    return acc.concat({ ...val, [childrenKey]: removeNode(val[childrenKey] || [], compareFn) });
  }, []);
}
