class RangeMap

A map that associates one or more ranges with a value for efficient lookup.

Definitions

def initialize

Initialize a new RangeMap.

Implementation

def initialize
	@entries = []
end

def add(ranges, value)

Add one or more ranges associated with a value to the map.

Signature

parameter ranges Range | Array(Range)

The ranges to map.

parameter value Object

The value to associate with the ranges.

returns Object

The added value.

Implementation

def add(ranges, value)
	ranges = [ranges] if ranges.is_a?(Range)
	@entries << [ranges, value]
	return value
end

def find(key)

Find the value associated with a key within any range.

Signature

parameter key Object

The key to find.

yields {...}

Block called if no range contains the key.

returns Object

The value if found, result of block if given, or nil.

Implementation

def find(key)
	@entries.each do |ranges, value|
		return value if ranges.any?{|range| range.include?(key)}
	end
	if block_given?
		return yield
	end
	return nil
end

def each

Iterate over each mapped value.

Signature

yields {|value| ...}

Block called for each value.

parameter value Object

The value associated with one or more ranges.

Implementation

def each
	@entries.each do |_, value|
		yield value
	end
end

def sample

Get a random value from the map.

Signature

returns Object

A randomly selected value, or nil if map is empty.

Implementation

def sample
	return nil if @entries.empty?
	_, value = @entries.sample
	return value
end

def clear

Clear all ranges from the map.

Implementation

def clear
	@entries.clear
end