-
-
Save baweaver/3552a966ab32670543a0c020a294d4e9 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
# 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