lib/regexp-examples/repeaters.rb in regexp-examples-1.0.2 vs lib/regexp-examples/repeaters.rb in regexp-examples-1.1.0

- old
+ new

@@ -1,14 +1,14 @@ module RegexpExamples class BaseRepeater - attr_reader :group + attr_reader :group, :min_repeats, :max_repeats def initialize(group) @group = group end - def result(min_repeats, max_repeats) - group_results = @group.result[0 .. RegexpExamples.MaxGroupResults-1] + def result + group_results = group.result[0 .. RegexpExamples.MaxGroupResults-1] results = [] min_repeats.upto(max_repeats) do |repeats| if repeats.zero? results << [ GroupResult.new('') ] else @@ -17,67 +17,61 @@ ) end end results.flatten.uniq end + + def random_result + result = [] + rand(min_repeats..max_repeats).times { result << group.random_result } + result << [ GroupResult.new('') ] if result.empty? # in case of 0.times + RegexpExamples::permutations_of_strings(result) + end end class OneTimeRepeater < BaseRepeater def initialize(group) super + @min_repeats = 1 + @max_repeats = 1 end - - def result - super(1, 1) - end end class StarRepeater < BaseRepeater def initialize(group) super + @min_repeats = 0 + @max_repeats = RegexpExamples.MaxRepeaterVariance end - - def result - super(0, RegexpExamples.MaxRepeaterVariance) - end end class PlusRepeater < BaseRepeater def initialize(group) super + @min_repeats = 1 + @max_repeats = RegexpExamples.MaxRepeaterVariance + 1 end - - def result - super(1, RegexpExamples.MaxRepeaterVariance + 1) - end end class QuestionMarkRepeater < BaseRepeater def initialize(group) super + @min_repeats = 0 + @max_repeats = 1 end - - def result - super(0, 1) - end end class RangeRepeater < BaseRepeater def initialize(group, min, has_comma, max) super(group) - @min = min || 0 - if max - # Prevent huge number of results in case of e.g. /.{1,100}/.examples - @max = smallest(max, @min + RegexpExamples.MaxRepeaterVariance) - elsif has_comma - @max = @min + RegexpExamples.MaxRepeaterVariance - else - @max = @min + @min_repeats = min || 0 + if max # e.g. {1,100} --> Treat as {1,3} or similar, to prevent a huge number of results + @max_repeats = smallest(max, @min_repeats + RegexpExamples.MaxRepeaterVariance) + elsif has_comma # e.g. {2,} --> Treat as {2,4} or similar + @max_repeats = @min_repeats + RegexpExamples.MaxRepeaterVariance + else # e.g. {3} --> Treat as {3,3} + @max_repeats = @min_repeats end - end - - def result - super(@min, @max) end private def smallest(x, y) (x < y) ? x : y