'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);

function excludeRepeatElements(obj) {
  return Object.keys(obj).reduce(function (acc, key) {
    acc[key] = Array.from(new Set(obj[key])).filter(function (item) {
      return item !== key;
    });
    return acc;
  }, {});
}
function realTraverse(list, map, result, originKey) {
  for (var _i = 0, _arr = _toConsumableArray__default["default"](list); _i < _arr.length; _i++) {
    var key = _arr[_i];
    if (result.indexOf(key) > -1) {
      continue;
    }
    result.push(key);
    var before = map[key];
    if (before) {
      before = before.filter(function (item) {
        return item !== originKey && list.indexOf(item) <= -1;
      });
      realTraverse(before, map, result, originKey);
    }
  }
}
/**
 * 将嵌套的依赖关系打平为一维映射
 * 递归遍历依赖关系图，将每个节点的所有直接和间接依赖打平为数组，并去重
 * @param {Record<string, Array<string>>} deps 依赖关系映射，key 为节点名，value 为其直接依赖的节点数组
 * @returns {Record<string, Array<string>>} 打平后的依赖关系映射
 * @example
 * ```ts
 * const deps = {
 *   a: ['b', 'c'],
 *   b: ['d'],
 *   c: [],
 *   d: [],
 * };
 * const result = getFlattenedDeps(deps);
 * // { a: ['b', 'c', 'd'], b: ['d'], c: [], d: [] }
 * ```
 */
function getFlattenedDeps(deps) {
  deps = excludeRepeatElements(deps);
  var list = Object.keys(deps);
  var newDeps = {};
  for (var _i2 = 0, _list = list; _i2 < _list.length; _i2++) {
    var item = _list[_i2];
    var temp = _toConsumableArray__default["default"](deps[item]);
    var result = [];
    realTraverse(_toConsumableArray__default["default"](temp), deps, result, item);
    newDeps[item] = result;
  }
  var res = excludeRepeatElements(newDeps);
  return res;
}

exports.getFlattenedDeps = getFlattenedDeps;
