0

This is what I came up with so far (it basically generates partitions as if it were a Cartesian product):

function partitions(str) {
  /**
   * @example
   * partitions('abc') // ["abc", "ab-c", "a-bc", "a-b-c"]
   *
   */
  const result = [];
  const sets = str.split('').map(x => [x, x + '-']);
  const max = sets.length - 1;
  // in this example: ['c', 'c-'] -> ['c'] (because it's the last character)
  sets[max].pop();

  function helper(arr, i) {
    for (let j = 0; j < sets[i].length; j++) {
      const c = arr.slice(0); // clone arr
      c.push(sets[i][j]);
      if (i === max) result.push(c.join('')); else helper(c, i + 1);
    }
  }

  helper([], 0);
  return result;
}

What is the correct way of implementing such function?

dreamski21
  • 17
  • 4

0 Answers0