import _ from "lodash";

const nest = (arr) => {
  const obj = {};
  arr.reduce((o, s) => (o[s] = {}), obj);
  return obj;
};

export const asTree = (branches) => {
  const nests = branches.map((b) => nest(b));
  return _.merge(...nests);
};

export const asBranches = (array) => {
  const merged = [];
  array.forEach((p, i) => {
    p.forEach((v, i) => {
      if (!merged[i]) merged[i] = [];
      if (!merged[i].includes(v)) merged[i].push(v);
    });
  });
  return merged;
};

export const as1d = (a) => [].concat.apply([], a);

export const selectBranch = (map, test) => {
  const pipeline = map.find((pm) => pm.includes(test));
  const testIndex = pipeline.findIndex((t) => t === test);
  return pipeline.slice(0, testIndex + 1);
};
