Class: Sorted::Set

Inherits:
Object
  • Object
show all
Includes:
Comparable, Enumerable
Defined in:
lib/sorted.rb

Instance Method Summary collapse

Constructor Details

#initialize(set = []) ⇒ Set

Returns a new instance of Set.



6
7
8
# File 'lib/sorted.rb', line 6

def initialize(set = [])
  @set = set
end

Instance Method Details

#+(other) ⇒ Object



54
55
56
# File 'lib/sorted.rb', line 54

def +(other)
  self.class.new(@set + other.to_a)
end

#-(other) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/sorted.rb', line 44

def -(other)
  self.class.new.tap do |memo|
    each do |a|
      b = other.assoc(a.first)
      next if b
      memo << a
    end
  end
end

#<<(other) ⇒ Object



58
59
60
# File 'lib/sorted.rb', line 58

def <<(other)
  self.class.new(@set << other.to_a)
end

#<=>(other) ⇒ Object



70
71
72
# File 'lib/sorted.rb', line 70

def <=>(other)
  @set <=> other.to_a
end

#assoc(o) ⇒ Object



78
79
80
# File 'lib/sorted.rb', line 78

def assoc(o)
  @set.assoc(o)
end

#at(i) ⇒ Object



82
83
84
# File 'lib/sorted.rb', line 82

def at(i)
  @set.at(i)
end

#direction_intersect(other) ⇒ Object

Returns a resulting set with specific keys flipped

a = Sorted::Set.new([['email', 'asc'], ['name', 'asc']])
b = Sorted::Set.new([['email', 'asc'], ['phone', 'asc']])
s = a.direction_intersect(b)
s.to_a #=> [['email', 'desc'], ['phone', 'asc'], ['name', 'asc']]


33
34
35
36
37
38
39
40
41
42
# File 'lib/sorted.rb', line 33

def direction_intersect(other)
  self.class.new.tap do |memo|
    unless other.keys.empty?
      a(memo, other)
      b(memo, other)
    end
    c(memo)
    d(memo, other)
  end
end

#each(&block) ⇒ Object



10
11
12
# File 'lib/sorted.rb', line 10

def each(&block)
  @set.each(&block)
end

#keysObject

Gets the keys from the array pairs

set = [["email", "name"], ["desc", "desc"]]
set.transpose #=> [["email", "name"], ["desc", "desc"]]
set.transpose.first #=> ["email", "name"]


21
22
23
# File 'lib/sorted.rb', line 21

def keys
  @set.transpose.first || []
end

#reject(&block) ⇒ Object



66
67
68
# File 'lib/sorted.rb', line 66

def reject(&block)
  self.class.new(@set.reject(&block))
end

#select(&block) ⇒ Object



62
63
64
# File 'lib/sorted.rb', line 62

def select(&block)
  self.class.new(@set.select(&block))
end

#to_aObject



86
87
88
# File 'lib/sorted.rb', line 86

def to_a
  @set
end

#to_hashObject



90
91
92
# File 'lib/sorted.rb', line 90

def to_hash
  @set.inject({}) { |a, e| a.merge(Hash[e[0], e[1]]) }
end

#uniqObject



74
75
76
# File 'lib/sorted.rb', line 74

def uniq
  self.class.new(@set.uniq)
end