1# frozen_string_literal: true
2
3# Uniquify
4#
5# Return a version of the given 'base' string that is unique
6# by appending a counter to it. Uniqueness is determined by
7# repeated calls to the passed block.
8#
9# You can pass an initial value for the counter, if not given
10# counting starts from 1.
11#
12# If `base` is a function/proc, we expect that calling it with a
13# candidate counter returns a string to test/return.
14class Uniquify
15  def initialize(counter = nil)
16    @counter = counter
17  end
18
19  def string(base)
20    @base = base
21
22    increment_counter! while yield(base_string)
23    base_string
24  end
25
26  private
27
28  def base_string
29    if @base.respond_to?(:call)
30      @base.call(@counter)
31    else
32      "#{@base}#{@counter}"
33    end
34  end
35
36  def increment_counter!
37    @counter ||= 0
38    @counter += 1
39  end
40end
41