Anonymous Anonymous - 1 month ago
93 1

No description

Javascript

const data = ["AB", "AD", "DB", "BC", "BS", "CE", "SE"];

const data = ["AB", "AD", "DB", "BC", "BS", "CE", "SE"];

const getRest = (a, i) => {
  if (i >= a.length) return a;
  if (i === a.length-1) return a.slice(0, i);
  if (i === 0) return a.slice(1);
  return a.slice(0, i).concat(a.slice(i+1));
}

const detectChains = (data) => {
  return data.reduce((a, e) => {
    a[e] = data.filter(s => s[0] === e[1]);
    return a;
  }, {});
}

const buildChains = (a, c) => {
  let n = 0;
  Object.keys(a).forEach(e => {
    const p = a[e];
    if (c[e]['length']) {
      delete a[e];
      c[e].forEach(cc => {
        a[cc] = p+cc;
      });
      n++;
    }
  });
  if (n>0) buildChains(a, c);
}

const i = 0;
const c = detectChains(data);
data.forEach(d => {
  const s = { [d]: d };
  buildChains(s, c);
  const ret = Object.keys(s).filter(key => s[key].length>2).map(key => s[key]);
  if (ret.length>0) console.log({ [d]: ret });
});