File: deduplicator.rb

package info (click to toggle)
ruby-roadie 5.2.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 528 kB
  • sloc: ruby: 3,418; makefile: 5
file content (49 lines) | stat: -rw-r--r-- 989 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# frozen_string_literal: true

module Roadie
  class Deduplicator
    def self.apply(input)
      new(input).apply
    end

    def initialize(input)
      @input = input
      @duplicates = false
    end

    def apply
      # Bail early for very small inputs
      input if input.size < 2

      calculate_latest_occurance

      # Another early bail in case we never even have a duplicate value
      if has_duplicates?
        strip_out_duplicates
      else
        input
      end
    end

    private

    attr_reader :input, :latest_occurance

    def has_duplicates?
      @duplicates
    end

    def calculate_latest_occurance
      @latest_occurance = input.each_with_index.each_with_object({}) do |(value, index), map|
        @duplicates = true if map.has_key?(value)
        map[value] = index
      end
    end

    def strip_out_duplicates
      input.each_with_index.select { |value, index|
        latest_occurance[value] == index
      }.map(&:first)
    end
  end
end