# Set is an unordered collection of unique values.
# Backed natively by an insertion-ordered Vec with linear deduplication.
# Construction: Set.new or Set.new([1, 2, 3])
#
class Set {
# Returns a new List built by calling the block once per element.
#
# Set.new([1, 2, 3]).map { |x| x * 2 } # [2, 4, 6]
#
def map {
result = []
each { |x| result.append(yield(x)) }
result
}
# Returns a new Set containing only elements for which the block returns true.
#
# Set.new([1, 2, 3, 4]).select { |x| x > 2 } # Set{3, 4}
#
def select {
result = Set.new
each { |x| result.add(x) if yield(x) }
result
}
# Returns a new Set containing elements for which the block returns false.
#
# Set.new([1, 2, 3]).reject { |x| x == 2 } # Set{1, 3}
#
def reject {
result = Set.new
each { |x| result.add(x) if !yield(x) }
result
}
# Returns true if the block returns truthy for at least one element.
#
# Set.new([1, 2, 3]).any? { |x| x > 2 } # true
#
def any?() {
each { |x| return true if yield(x) }
false
}
# Returns true if the block returns truthy for every element. Empty sets are true.
#
# Set.new([1, 2, 3]).all? { |x| x > 0 } # true
#
def all?() {
each { |x| return false if !yield(x) }
true
}
# Returns true if the block never returns truthy. Empty sets are true.
#
# Set.new([1, 2, 3]).none? { |x| x > 9 } # true
#
def none?() {
each { |x| return false if yield(x) }
true
}
# Yields each element with its zero-based insertion index.
#
# Set.new(["a", "b"]).each_with_index { |item, i| print "#{i}: #{item}" }
#
def each_with_index {
i = 0
each { |x|
yield(x, i)
i = i + 1
}
}
}