Created
August 3, 2021 10:53
-
-
Save nivb52/47fd68300d430faf62e80748f5cb65ad to your computer and use it in GitHub Desktop.
extract Unique Values From Collection by property using sets and funtion or instruction per property
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
| /** | |
| * @param collection {[]} | |
| * @param properties {String[]} | |
| * @param options {{return_as_arrays: (Boolean), : {extract_instruction: (String), extract_function: (Function)}}} | |
| * @example: | |
| * transport_items_data, | |
| * ['transport_item_type_id', 'status_ids_for_filtering', 'status_ids'], | |
| * {return_as_arrays: true, status_ids_for_filtering: {extract_instruction: 'spread'}, status_ids: {extract_instruction: 'spread'}} | |
| * @returns {Object} | |
| */ | |
| _.extractUniqueValuesFromCollection = (collection, properties, options = {}) => { | |
| const sets_repo = {}; | |
| properties.forEach(property => sets_repo[property] = new Set()); | |
| collection.forEach(item => { | |
| properties.forEach(property => { | |
| if (options[property]){ | |
| if (options[property].extract_instruction === 'spread'){ | |
| sets_repo[property].add(...item[property]) | |
| } else { | |
| const extract_function = options[property].extract_function; | |
| sets_repo[property].add(extract_function(item[property])); | |
| } | |
| } else { | |
| sets_repo[property].add(item[property]) | |
| } | |
| } | |
| ); | |
| }); | |
| const results = {}; | |
| if (options.return_as_arrays) { | |
| Object.keys(sets_repo).forEach(key => | |
| results[key] = Array.from(sets_repo[key]) | |
| ); | |
| } | |
| return options.return_as_arrays ? | |
| results : | |
| sets_repo; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment