Created
October 4, 2016 01:44
-
-
Save jenrzzz/02a182a8800b0c7201269f996fb92067 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Public: A fancy class for doing complicated group-bys. | |
# Construct it with a strategy object that responds to #key_for, #set, and | |
# #default_accumulator. | |
class Aggregator | |
attr_reader :strategy | |
# Public: Create a new Aggregator. | |
# | |
# strategy - An aggregation strategy object that responds to the following: | |
# #key_for(item) - takes an item from the collection and returns the key to use for it. | |
# #set(acc, value, key, collection) - takes the accumulator, key, and item | |
# and sets it appropriately. `collection` is the entire collection being aggregated. | |
def initialize(strategy) | |
@strategy = strategy | |
end | |
# Public: Aggregate an enumerable collection. | |
# collection - the collection to aggregate. Must respond to #each. | |
# accummulator - (optional) an accumulator object to use (defaults to the default | |
# accumulator defined in the strategy) | |
# | |
# Returns the resulting accumulator after #set has been called for each item | |
# in the `collection`. | |
def aggregate(collection, accumulator = strategy.default_accumulator) | |
collection.each do |value| | |
strategy.set(accumulator, value, strategy.key_for(value), collection) | |
end | |
accumulator | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment