Mange / roadie
1
# frozen_string_literal: true
2

3 5
module Roadie
4 5
  class Deduplicator
5 5
    def self.apply(input)
6 5
      new(input).apply
7
    end
8

9 5
    def initialize(input)
10 5
      @input = input
11 5
      @duplicates = false
12
    end
13

14 5
    def apply
15
      # Bail early for very small inputs
16 5
      input if input.size < 2
17

18 5
      calculate_latest_occurance
19

20
      # Another early bail in case we never even have a duplicate value
21 5
      if has_duplicates?
22 5
        strip_out_duplicates
23
      else
24 5
        input
25
      end
26
    end
27

28 5
    private
29 5
    attr_reader :input, :latest_occurance
30

31 5
    def has_duplicates?
32 5
      @duplicates
33
    end
34

35 5
    def calculate_latest_occurance
36 5
      @latest_occurance = input.each_with_index.each_with_object({}) do |(value, index), map|
37 5
        @duplicates = true if map.has_key?(value)
38 5
        map[value] = index
39
      end
40
    end
41

42 5
    def strip_out_duplicates
43 3
      input.each_with_index.select { |value, index|
44 5
        latest_occurance[value] == index
45 2
      }.map(&:first)
46
    end
47
  end
48
end

Read our documentation on viewing source code .

Loading