
/**
 * 数组 转 Tree
 * @param {*} arr 
 * @param {*} parent 
 * @param {*} key 
 * @returns 
 */
export function arr2Tree(arr = [], parent = 'parentId', key = 'key') {
  // 转换为字典
  const dict = arr.reduce((acc, item) => {
    return {
      ...acc,
      [item[key]]: {
        ...item,
        children: []
      }
    }
  }, {});

  // 挂载父子节点
  const tree = [];
  for (let item of arr) {
    const it = dict[item[key]];
    const parentNodeId = it[parent];
    const parentNode = dict[parentNodeId];

    if (!parentNode) {
      tree.push(it);
    } else {
      dict[parentNodeId].children.push(it);
    }
  }

  return [tree, dict];
}

/**
 * 深度展平数组
 * @param {*} arr 
 * @returns 
 */
export function flatten(arr = []) {
  return arr.reduce((acc, it) => {
    const list = Array.isArray(it) ? flatten(it) : it
    return acc.concat(list);
  }, []);
}

/**
 * 深度数组去重
 * @param {*} arr 
 */
export function uniq(arr = []) {
  const list = flatten(arr);
  return list.reduce((acc, it) => {
    return acc.indexOf(it) > -1 ? acc : acc.concat(it)
  }, []);
}

