Sha256: 30ceb87f875030557089099bcea17625b342c4ae6f746e1641c26b2fc3d9fbbd

Contents?: true

Size: 1.23 KB

Versions: 11

Compression:

Stored size: 1.23 KB

Contents

module RegexpExamples
  # Given an array of arrays of strings,
  # returns all possible perutations,
  # for strings created by joining one
  # element from each array
  #
  # For example:
  # permutations_of_strings [ ['a'], ['b'], ['c', 'd', 'e'] ] #=> ['abc', 'abd', 'abe']
  # permutations_of_strings [ ['a', 'b'], ['c', 'd'] ] #=> [ 'ac', 'ad', 'bc', 'bd' ]
  def self.permutations_of_strings(arrays_of_strings)
    first = arrays_of_strings.shift
    return first if arrays_of_strings.empty?
    first.product( permutations_of_strings(arrays_of_strings) ).map do |result|
      join_preserving_capture_groups(result)
    end
  end

  def self.join_preserving_capture_groups(result)
    result.flatten!
    subgroups = result
      .map(&:all_subgroups)
      .flatten

    # Only save the LAST group from repeated capture groups, e.g. /([ab]){2}/
    subgroups.delete_if do |subgroup|
      subgroups.count { |other_subgroup| other_subgroup.group_id == subgroup.group_id } > 1
    end
    GroupResult.new(result.join, nil, subgroups)
  end

  def self.map_results(repeaters)
    repeaters
      .map {|repeater| repeater.result}
      .instance_eval do |partial_results|
        RegexpExamples.permutations_of_strings(partial_results)
      end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
regexp-examples-1.0.2 lib/regexp-examples/helpers.rb
regexp-examples-1.0.1 lib/regexp-examples/helpers.rb
regexp-examples-1.0.0 lib/regexp-examples/helpers.rb
regexp-examples-0.7.0 lib/regexp-examples/helpers.rb
regexp-examples-0.6.0 lib/regexp-examples/helpers.rb
regexp-examples-0.5.4 lib/regexp-examples/helpers.rb
regexp-examples-0.5.3 lib/regexp-examples/helpers.rb
regexp-examples-0.5.2 lib/regexp-examples/helpers.rb
regexp-examples-0.5.1 lib/regexp-examples/helpers.rb
regexp-examples-0.5.0 lib/regexp-examples/helpers.rb
regexp-examples-0.4.2 lib/regexp-examples/helpers.rb