Created
November 19, 2018 18:19
-
-
Save mizhi/e52945f93d61d4b8fce81434f0debcd9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| # *=== Monday Nov 19th 2018 - Daily Programmer ===* | |
| # *[Message Grouping]* | |
| # * This is a real life problem that @Julian Flynn tried to solve last week for his app. | |
| # There are two types of messages: `sub` and `entry`. | |
| # The `sub` entries group the following `sub` entries within its `group`. | |
| # Examples: | |
| # ```input = [ | |
| # { id: 1, type: 'sub', group: [] }, | |
| # { id: 2, type: 'sub', group: [] }, | |
| # { id: 3, type: 'entry' }, | |
| # ] | |
| # output = [ | |
| # { id: 1, type: 'sub', group: [{ id: 2, type: 'sub', group: [] }] }, | |
| # { id: 3, type: 'entry' } | |
| # ]``` | |
| # ```input = [ | |
| # { id: 1, type: 'sub', group: [] }, | |
| # { id: 2, type: 'sub', group: [] }, | |
| # { id: 3, type: 'sub', group: [] }, | |
| # { id: 4, type: 'entry' }, | |
| # { id: 5, type: 'sub', group: [] }, | |
| # { id: 6, type: 'entry' }, | |
| # { id: 7, type: 'sub', group: [] }, | |
| # { id: 8, type: 'sub', group: [] }, | |
| # ] | |
| # output = [ | |
| # { id: 1, type: 'sub', group: [{ id: 2, type: 'sub', group: [] }, { id: 3, type: 'sub', group: [] }] }, | |
| # { id: 4, type: 'entry' }, | |
| # { id: 5, type: 'sub', group: [] }, | |
| # { id: 6, type: 'entry' }, | |
| # { id: 7, type: 'sub': group: [{ id: 8, type: 'sub', group: [] }] }, | |
| # ]``` | |
| def group_subs(records) | |
| records | |
| .chunk { |record| record[:type] } # give [type, [record1, record2]], ... | |
| .map do |type, type_records| | |
| if type == "sub" | |
| type_records.first.merge(group: type_records.drop(1)) | |
| else | |
| type_records.first | |
| end | |
| end | |
| end | |
| INPUTS = [ | |
| { id: 1, type: 'sub', group: [] }, | |
| { id: 2, type: 'sub', group: [] }, | |
| { id: 3, type: 'sub', group: [] }, | |
| { id: 4, type: 'entry' }, | |
| { id: 5, type: 'sub', group: [] }, | |
| { id: 6, type: 'entry' }, | |
| { id: 7, type: 'sub', group: [] }, | |
| { id: 8, type: 'sub', group: [] }, | |
| ] | |
| puts group_subs(INPUTS).to_a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment