Skip to content

Instantly share code, notes, and snippets.

@baweaver
Created April 5, 2016 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baweaver/3552a966ab32670543a0c020a294d4e9 to your computer and use it in GitHub Desktop.
Save baweaver/3552a966ab32670543a0c020a294d4e9 to your computer and use it in GitHub Desktop.
# Chunk is going to introduce the concept of passing "state" through reduce
def r_chunk
data = reduce({
result: [],
stack: []
}) { |state, item|
new_value = yield(item)
if state[:stack].empty?
stack = [new_value, [item]]
else
previous_value, collection = state[:stack]
if new_value == previous_value
stack = [new_value, [*collection, item]]
else
result = [*state[:result], state[:stack]]
stack = [new_value, [item]]
end
end
{result: result, stack: stack}
}
[*data[:result], data[:stack]]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment