Class: Set

Inherits:
Object show all
Includes:
Enumerable
Defined in:
opal/stdlib/set.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Enumerable

#to_set

Constructor Details

#initialize(enum = nil, &block) ⇒ Set

Returns a new instance of Set



8
9
10
11
12
13
14
15
16
17
18
# File 'opal/stdlib/set.rb', line 8

def initialize(enum = nil, &block)
  @hash = Hash.new

  return if enum.nil?

  if block
    do_with_enum(enum) { |o| add(block[o]) }
  else
    merge(enum)
  end
end

Class Method Details

.[](*ary) ⇒ Object



4
5
6
# File 'opal/stdlib/set.rb', line 4

def self.[](*ary)
  new(ary)
end

Instance Method Details

#==(other) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
# File 'opal/stdlib/set.rb', line 20

def ==(other)
  if self.equal?(other)
    true
  elsif other.instance_of?(self.class)
    @hash == other.instance_variable_get(:@hash)
  elsif other.is_a?(Set) && self.size == other.size
    other.all? { |o| @hash.include?(o) }
  else
    false
  end
end

#add(o) ⇒ Object Also known as: <<



32
33
34
35
# File 'opal/stdlib/set.rb', line 32

def add(o)
  @hash[o] = true
  self
end

#add?(o) ⇒ Boolean

Returns:



38
39
40
41
42
43
44
# File 'opal/stdlib/set.rb', line 38

def add?(o)
  if include?(o)
    nil
  else
    add(o)
  end
end

#clearObject



56
57
58
59
# File 'opal/stdlib/set.rb', line 56

def clear
  @hash.clear
  self
end

#do_with_enum(enum, &block) ⇒ Object



71
72
73
# File 'opal/stdlib/set.rb', line 71

def do_with_enum(enum, &block)
  enum.each(&block)
end

#each(&block) ⇒ Object



46
47
48
49
50
# File 'opal/stdlib/set.rb', line 46

def each(&block)
  return enum_for :each unless block_given?
  @hash.each_key(&block)
  self
end

#empty?Boolean

Returns:



52
53
54
# File 'opal/stdlib/set.rb', line 52

def empty?
  @hash.empty?
end

#include?(o) ⇒ Boolean Also known as: member?

Returns:



61
62
63
# File 'opal/stdlib/set.rb', line 61

def include?(o)
  @hash.include?(o)
end

#merge(enum) ⇒ Object



66
67
68
69
# File 'opal/stdlib/set.rb', line 66

def merge(enum)
  do_with_enum(enum) { |o| add o }
  self
end

#sizeObject Also known as: length



75
76
77
# File 'opal/stdlib/set.rb', line 75

def size
  @hash.size
end

#to_aObject



80
81
82
# File 'opal/stdlib/set.rb', line 80

def to_a
  @hash.keys
end