array_collection 0.2.7

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 899d9a37325bf46eb9d86e8ab0729df54dc5fae5edaf83217645a9349980fd88
4
+ data.tar.gz: cddb4997199a58f12e83dab9f39c991a2aac73f310b94e1b0d26b251bd4b144f
5
+ SHA512:
6
+ metadata.gz: 3061ecca55b37ec8ee1a4cc281c918fb1fdf73d2e0c2e49b36c829339d0a26bd4667a37d041418b0b954f114e7a5febd9a1a8840a2197fc237496917382c9208
7
+ data.tar.gz: a2d485225606222d0785451dea0e6e7488f1deab5715d8edcbf29adc92af5280f51e0fbc2326f63600cea9aa0155143a44487010a1276bacf62e874c9a737cce
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,25 @@
1
+ require:
2
+ - rubocop-rspec
3
+ - rubocop-rake
4
+
5
+ AllCops:
6
+ TargetRubyVersion: 3.0
7
+ NewCops: enable
8
+
9
+ Style/StringLiterals:
10
+ Enabled: true
11
+ EnforcedStyle: double_quotes
12
+
13
+ Style/StringLiteralsInInterpolation:
14
+ Enabled: true
15
+ EnforcedStyle: double_quotes
16
+
17
+ Layout/LineLength:
18
+ Max: 120
19
+
20
+ Metrics/BlockLength:
21
+ Exclude:
22
+ - spec/**/*.rb
23
+
24
+ RSpec/ExampleLength:
25
+ Enabled: false
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.2.2
data/.versionrc.js ADDED
@@ -0,0 +1,20 @@
1
+ const version_rb = {
2
+ filename: "lib/collection/version.rb",
3
+ updater: {
4
+ readVersion: function (contents) {
5
+ const match = contents.match(/^\s*VERSION = ["'](.+)["']$/m);
6
+ return match[1];
7
+ },
8
+ writeVersion: function (contents, version) {
9
+ const currentVersion = this.readVersion(contents);
10
+ // this isn't the most reliable, but meh
11
+ return contents.replace(currentVersion, version);
12
+ },
13
+ },
14
+ };
15
+
16
+ module.exports = {
17
+ bumpFiles: [version_rb],
18
+ packageFiles: [version_rb],
19
+ preset: "angular",
20
+ };
data/CHANGELOG.md ADDED
@@ -0,0 +1,75 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
+
5
+ ## [0.2.10](https://github.com/WailanTirajoh/ruby_collection/compare/v0.2.9...v0.2.10) (2024-03-26)
6
+
7
+
8
+ ### Bug Fixes
9
+
10
+ * **gem:** remove required mfa ([7b4b9c4](https://github.com/WailanTirajoh/ruby_collection/commit/7b4b9c432002ff4381da0004d3ad4d6912b8b2d8))
11
+ * **gem:** remove required mfa ([d342636](https://github.com/WailanTirajoh/ruby_collection/commit/d3426369e6f1dff96abc568689fc9ec4381967f1))
12
+
13
+
14
+
15
+ ## [0.2.9](https://github.com/WailanTirajoh/ruby_collection/compare/v0.2.8...v0.2.9) (2024-03-26)
16
+
17
+
18
+
19
+ ## [0.2.8](https://github.com/WailanTirajoh/ruby_collection/compare/v0.2.7...v0.2.8) (2024-03-26)
20
+
21
+
22
+ ### Bug Fixes
23
+
24
+ * **lint:** Lintfix ([be99af7](https://github.com/WailanTirajoh/ruby_collection/commit/be99af72b9f3a2cfadad224aff191aafb48a6d45))
25
+
26
+
27
+
28
+ ## [0.2.7](https://github.com/WailanTirajoh/ruby_collection/compare/v0.2.6...v0.2.7) (2024-03-26)
29
+
30
+
31
+
32
+ ## [0.2.6](https://github.com/WailanTirajoh/ruby_collection/compare/v0.2.5...v0.2.6) (2024-03-26)
33
+
34
+
35
+
36
+ ## [0.2.5](https://github.com/WailanTirajoh/ruby_collection/compare/v0.2.4...v0.2.5) (2024-03-26)
37
+
38
+
39
+
40
+ ## [0.2.4](https://github.com/WailanTirajoh/ruby_collection/compare/v0.2.3...v0.2.4) (2024-03-26)
41
+
42
+
43
+
44
+ ## [0.2.3](https://github.com/WailanTirajoh/ruby_collection/compare/v0.2.2...v0.2.3) (2024-03-26)
45
+
46
+
47
+
48
+ ## [0.2.2](https://github.com/WailanTirajoh/ruby_collection/compare/v0.2.1...v0.2.2) (2024-03-26)
49
+
50
+
51
+
52
+ ## [0.2.1](https://github.com/WailanTirajoh/ruby_collection/compare/v0.2.0...v0.2.1) (2024-03-26)
53
+
54
+
55
+
56
+ # 0.2.0 (2024-03-26)
57
+
58
+
59
+ ### Features
60
+
61
+ * **collect:** add left_join, right_join, full_join ([bca2af5](https://github.com/WailanTirajoh/ruby_collection/commit/bca2af5ec5e9b078fb7c75155ae0e1f79e8e1732))
62
+ * **collection:** add sort, append, prepend, map and test chainable collection ([8084fc9](https://github.com/WailanTirajoh/ruby_collection/commit/8084fc966b2a3540c3e5f8935b56d795d8bf8b69))
63
+ * **collection:** first initial collection & array fn ([2009281](https://github.com/WailanTirajoh/ruby_collection/commit/2009281a2d53d8ffa4a0090fd4e363329ac0f4ed))
64
+ * **collection:** first initial collection & array fn ([04efd77](https://github.com/WailanTirajoh/ruby_collection/commit/04efd77f32bae72e1ad53391744bbfde12123754))
65
+ * **data:** data accessor based on dot notation ([92efb9e](https://github.com/WailanTirajoh/ruby_collection/commit/92efb9e48f6dbeeb72c3f2bc1090bd4cd9f903c2))
66
+ * **diff:** add diff & refactor array spec ([d0e3a66](https://github.com/WailanTirajoh/ruby_collection/commit/d0e3a66c8bd2d6d4f7ba706537b01e18929a3d51))
67
+ * **helper:** add collect helper ([13c4efb](https://github.com/WailanTirajoh/ruby_collection/commit/13c4efbbc481960227f361208818471a197df752))
68
+ * **join:** inner join ([d1f011b](https://github.com/WailanTirajoh/ruby_collection/commit/d1f011b76560ad26fdecdef1c01cdc7291cbac6e))
69
+ * **utils:** add when, only, except ([77da9e8](https://github.com/WailanTirajoh/ruby_collection/commit/77da9e848ae60b771f24cf623b73df85f80b1eea))
70
+
71
+
72
+
73
+ ## [0.1.0] - 2024-03-15
74
+
75
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at wailantirajoh@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Wailan Tirajoh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,109 @@
1
+ # Collection Module
2
+
3
+ The `Collection` module provides utility functions for working with arrays.
4
+
5
+ ## Usage
6
+
7
+ ### Collect Class
8
+
9
+ The `Collect` class is used to create chainable collections for easy manipulation of arrays.
10
+
11
+ #### Before
12
+
13
+ ```ruby
14
+ items = [
15
+ { a: 3, b: 1, x: [1, 2, 3] },
16
+ { a: 1, b: 2, x: [] },
17
+ { a: 2, b: 3, x: [2, 3] },
18
+ nil
19
+ ]
20
+
21
+ # Remove nil items
22
+ items.compact!
23
+
24
+ # Filter items where :a is greater than 1
25
+ items.select! { |item| item[:a] > 1 }
26
+
27
+ # Append { a: 0, b: 2 } if specified
28
+ items << { a: 0, b: 2 } if params[:should_append]
29
+
30
+ # Prepend { a: 4, b: 2 }
31
+ items.unshift({ a: 4, b: 2 })
32
+
33
+ # Sort items by :a
34
+ items.sort_by! { |item| item[:a] }
35
+
36
+ # Map items to new structure
37
+ items.map! do |item|
38
+ {
39
+ a: item[:a],
40
+ b: item[:b],
41
+ c: item[:a] + item[:b],
42
+ x: item[:x].sort
43
+ }
44
+ end
45
+ ```
46
+
47
+ #### After
48
+
49
+ ```ruby
50
+ collect(items)
51
+ .where_not_nil
52
+ .where(:a, ">", 1)
53
+ .when(params[:should_append]) do |collections|
54
+ collections.append({ a: 0, b: 2 })
55
+ end
56
+ .prepend({ a: 4, b: 2 })
57
+ .sort_by_key(:a)
58
+ .map do |item|
59
+ {
60
+ a: item[:a],
61
+ b: item[:b],
62
+ c: item[:a] + item[:b],
63
+ x: collect(item[:x]).sort.all
64
+ }
65
+ end
66
+ .all
67
+ ```
68
+
69
+ #### Example:
70
+
71
+ ##### Filter
72
+
73
+ ```ruby
74
+ include ArrayCollection::Helper # Include collection helper to call collect only instead of ArrayCollection::collect.new
75
+
76
+ # Create a new collection
77
+ collect([1, 2, 3, 4, 5]).filter { |item| item > 2 }.all
78
+ # => [3, 4, 5]
79
+ ```
80
+
81
+ ##### Where
82
+
83
+ ```ruby
84
+ include ArrayCollection::Helper
85
+
86
+ # Create a new collection
87
+ collect([
88
+ { name: 'Alice', age: 30 },
89
+ { name: 'Bob', age: 25 }
90
+ ]).where(:age, '>', 25)
91
+ .all
92
+ # => [{ name: 'Alice', age: 30 }]
93
+ ```
94
+
95
+ ##### Where not nil
96
+
97
+ ```ruby
98
+ result = collect([1, 2, nil, 3, 4, nil, 5])
99
+ .where_not_nil
100
+ .all
101
+ # => [1, 2, 3, 4, 5]
102
+ ```
103
+
104
+ ##### index_of
105
+
106
+ ```ruby
107
+ collect([1, 2, 3, 4, 2]).index_of(2)
108
+ # => 1
109
+ ```
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/array_collection/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "array_collection"
7
+ spec.version = ArrayCollection::VERSION
8
+ spec.authors = ["Wailan Tirajoh"]
9
+ spec.email = ["wailantirajoh@gmail.com"]
10
+
11
+ spec.summary = "gem for array collection"
12
+ spec.description = "Write a longer description or delete this line."
13
+ spec.homepage = "https://github.com/WailanTirajoh/ruby_collection"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 3.0.0"
16
+
17
+ # spec.metadata["allowed_push_host"] = "Set to your gem server 'https://example.com'"
18
+
19
+ # spec.metadata["homepage_uri"] = spec.homepage
20
+ # spec.metadata["source_code_uri"] = "https://github.com/WailanTirajoh/ruby_collection"
21
+ spec.metadata["changelog_uri"] = "https://github.com/WailanTirajoh/ruby_collection/CHANGELOG.md"
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(__dir__) do
26
+ `git ls-files -z`.split("\x0").reject do |f|
27
+ (File.expand_path(f) == __FILE__) ||
28
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git .github appveyor Gemfile])
29
+ end
30
+ end
31
+ spec.bindir = "exe"
32
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
33
+ spec.require_paths = ["lib"]
34
+
35
+ # Uncomment to register a new dependency of your gem
36
+ # spec.add_dependency "example-gem", "~> 1.0"
37
+ end
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "collection_array"
4
+ require_relative "hooks"
5
+
6
+ module ArrayCollection
7
+ # Set of chainable collections
8
+ class Collect
9
+ extend ArrayCollection::Hooks
10
+
11
+ def initialize(items)
12
+ @items = get_arrayable_items(items)
13
+ end
14
+
15
+ def all
16
+ @items
17
+ end
18
+
19
+ def filter(&block)
20
+ self.class.new(ArrayCollection::CollectionArray.filter(@items, &block))
21
+ end
22
+
23
+ def where(key, *args)
24
+ self.class.new(ArrayCollection::CollectionArray.where(@items, key, *args))
25
+ end
26
+
27
+ def where_not_nil
28
+ self.class.new(ArrayCollection::CollectionArray.where_not_nil(@items))
29
+ end
30
+
31
+ def index_of(value)
32
+ @items.index(value)
33
+ end
34
+
35
+ def key_by(key, &block)
36
+ ArrayCollection::CollectionArray.key_by(@items, key, &block)
37
+ end
38
+
39
+ def sort(&block)
40
+ self.class.new(@items.sort(&block))
41
+ end
42
+
43
+ def sort_desc(&block)
44
+ self.class.new(@items.sort(&block).reverse)
45
+ end
46
+
47
+ def sort_by_key(key)
48
+ self.class.new(@items.sort_by { |item| item[key] })
49
+ end
50
+
51
+ def append(value)
52
+ self.class.new(ArrayCollection::CollectionArray.append(@items, value))
53
+ end
54
+
55
+ def prepend(value)
56
+ self.class.new(ArrayCollection::CollectionArray.prepend(@items, value))
57
+ end
58
+
59
+ def map(&block)
60
+ self.class.new(ArrayCollection::CollectionArray.map(@items, &block))
61
+ end
62
+
63
+ def when(boolean)
64
+ return self if boolean == false
65
+
66
+ yield(self)
67
+ end
68
+
69
+ def only(*keys)
70
+ self.class.new(ArrayCollection::CollectionArray.only(@items, *keys))
71
+ end
72
+
73
+ def except(*keys)
74
+ self.class.new(ArrayCollection::CollectionArray.except(@items, *keys))
75
+ end
76
+
77
+ def diff(items)
78
+ self.class.new(ArrayCollection::CollectionArray.diff(@items, items))
79
+ end
80
+
81
+ def inner_join(items, left_key, right_key)
82
+ self.class.new(ArrayCollection::CollectionArray.inner_join(@items, get_arrayable_items(items), left_key,
83
+ right_key))
84
+ end
85
+
86
+ def left_join(items, left_key, right_key)
87
+ self.class.new(ArrayCollection::CollectionArray.left_join(@items, get_arrayable_items(items), left_key,
88
+ right_key))
89
+ end
90
+
91
+ def right_join(items, left_key, right_key)
92
+ self.class.new(ArrayCollection::CollectionArray.right_join(@items, get_arrayable_items(items), left_key,
93
+ right_key))
94
+ end
95
+
96
+ def full_join(items, left_key, right_key)
97
+ self.class.new(ArrayCollection::CollectionArray.full_join(@items, get_arrayable_items(items), left_key,
98
+ right_key))
99
+ end
100
+
101
+ private
102
+
103
+ def get_arrayable_items(items)
104
+ case items
105
+ when Array
106
+ items
107
+ when ArrayCollection::Collect
108
+ items.all
109
+ else
110
+ items.to_a
111
+ end
112
+ end
113
+
114
+ def check_hash_item
115
+ raise ArgumentError, "Input must be an array of hashes" unless @items.all? { |item| item.is_a?(Hash) }
116
+ end
117
+
118
+ # Hooks
119
+ before :key_by, :check_hash_item
120
+ before :only, :check_hash_item
121
+ end
122
+ end
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "collection_filter"
4
+
5
+ module ArrayCollection
6
+ # Sets of array utilities methods
7
+ class CollectionArray
8
+ class << self
9
+ def filter(array, &block)
10
+ array.select(&block)
11
+ end
12
+
13
+ def where(array, *args)
14
+ if args.size == 2
15
+ key, value = args
16
+ array.select { |item| item[key] == value }
17
+ elsif args.size == 3
18
+ key, operator, value = args
19
+ array.select { |item| ArrayCollection::CollectionFilter.apply_operator(operator, item[key], value) }
20
+ else
21
+ raise ArgumentError, "Invalid number of arguments"
22
+ end
23
+ end
24
+
25
+ def where_not_nil(array)
26
+ array.compact
27
+ end
28
+
29
+ def wrap(value)
30
+ return [] if value.nil?
31
+ return value if value.is_a?(Array)
32
+
33
+ [value]
34
+ end
35
+
36
+ def append(array, *elements)
37
+ array + elements
38
+ end
39
+
40
+ def prepend(array, *elements)
41
+ elements + array
42
+ end
43
+
44
+ def map(array, &block)
45
+ array.map(&block)
46
+ end
47
+
48
+ def map_with_keys(hash, &block)
49
+ hash.transform_values(&block)
50
+ end
51
+
52
+ def key_by(records, key)
53
+ records.to_h { |record| [record[key].to_s, yield(record)] }
54
+ end
55
+
56
+ def except(array, *keys)
57
+ raise ArgumentError, "Empty key list" if keys.empty?
58
+
59
+ array.map { |hash| hash.except(*keys) }
60
+ end
61
+
62
+ def only(array, *keys)
63
+ raise ArgumentError, "Empty key list" if keys.empty?
64
+
65
+ array.map { |hash| hash.select { |k, _| keys.include?(k) } }
66
+ end
67
+
68
+ def diff(array1, array2)
69
+ (array1 - array2) | (array2 - array1)
70
+ end
71
+
72
+ def join(array1, array2, key1, key2)
73
+ inner_join(array1, array2, key1, key2)
74
+ end
75
+
76
+ def inner_join(array1, array2, key1, key2)
77
+ array1.reject do |item1|
78
+ matching_items = array2.select { |item2| item1[key1] == item2[key2] }
79
+ matching_items.each { |matched_item| item1.merge!(matched_item) }
80
+ matching_items.empty?
81
+ end
82
+ end
83
+
84
+ def left_join(array1, array2, key1, key2)
85
+ return array1 if array2.count.zero?
86
+
87
+ right_index = build_index(array2, key2)
88
+
89
+ result = []
90
+ array1.each do |left_item|
91
+ right_items = right_index[left_item[key1]] || [nil_attributes(array2)]
92
+ merge_items(result, left_item, right_items)
93
+ end
94
+ result
95
+ end
96
+
97
+ def right_join(array1, array2, key1, key2)
98
+ left_index = build_index(array1, key1)
99
+
100
+ result = []
101
+ array2.each do |right_item|
102
+ left_items = left_index[right_item[key2]] || [nil_attributes(array1)]
103
+ merge_items(result, right_item, left_items)
104
+ end
105
+ result
106
+ end
107
+
108
+ def full_join(array1, array2, key1, key2)
109
+ left_join_result = left_join(array1, array2, key1, key2)
110
+ right_join_result = right_join(array1, array2, key1, key2)
111
+
112
+ left_join_result.concat(right_join_result).uniq
113
+ end
114
+
115
+ def full_outter_join(array1, array2, key1, key2)
116
+ full_join(array1, array2, key1, key2)
117
+ end
118
+
119
+ private
120
+
121
+ def build_index(array, key)
122
+ array.group_by { |item| item[key] }
123
+ end
124
+
125
+ def merge_items(result, left_item, right_items)
126
+ right_items.each do |right_item|
127
+ result << left_item.merge(right_item)
128
+ end
129
+ end
130
+
131
+ def nil_attributes(array)
132
+ array.first.keys.each_with_object({}) { |key, hash| hash[key] = nil }
133
+ end
134
+ end
135
+ end
136
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ArrayCollection
4
+ class UnsupportedOperator < ArgumentError; end
5
+
6
+ # filterable item using operators
7
+ class CollectionFilter
8
+ OPERATORS = {
9
+ "=" => ->(a, b) { a == b },
10
+ "==" => ->(a, b) { a == b },
11
+ "!=" => ->(a, b) { a != b },
12
+ "<>" => ->(a, b) { a != b },
13
+ ">" => ->(a, b) { a > b },
14
+ ">=" => ->(a, b) { a >= b },
15
+ "<" => ->(a, b) { a < b },
16
+ "<=" => ->(a, b) { a <= b },
17
+ "LIKE" => ->(a, b) { a.to_s.include?(b.to_s) },
18
+ "NOT LIKE" => ->(a, b) { !a.to_s.include?(b.to_s) }
19
+ }.freeze
20
+
21
+ def self.apply_operator(operator, a, b) # rubocop:disable Naming/MethodParameterName
22
+ operator_lambda = OPERATORS[operator.upcase]
23
+ unless operator_lambda
24
+ raise UnsupportedOperator,
25
+ "Unsupported operator: #{operator}, current supported operator: #{OPERATORS.keys}"
26
+ end
27
+
28
+ operator_lambda.call(a, b)
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ArrayCollection
4
+ # Data retreiver based on string dot notation
5
+ class DataAccessor
6
+ class << self
7
+ # TODO: Refactor
8
+ def get(target, key, default = nil) # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/MethodLength,Metrics/PerceivedComplexity
9
+ return target if key.nil?
10
+
11
+ key = key.split(".") unless key.is_a?(Array)
12
+
13
+ key.each_with_index do |segment, i|
14
+ return target if segment.nil?
15
+
16
+ if segment == "*"
17
+ return default unless target.is_a?(Array)
18
+
19
+ result = target.map { |item| get(item, key[i + 1..]) }
20
+ return key.include?("*") ? result.flatten : result
21
+ end
22
+
23
+ segment = if segment.to_i.to_s == segment
24
+ segment.to_i
25
+ else
26
+ segment.to_sym
27
+ end
28
+ if target.respond_to?(:[]) && target[segment]
29
+ target = target[segment]
30
+ elsif target.respond_to?(segment)
31
+ target = target.send(segment)
32
+ else
33
+ return default
34
+ end
35
+ end
36
+
37
+ target
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "collect"
4
+
5
+ module ArrayCollection
6
+ # Expose collect
7
+ module Helper
8
+ module_function
9
+
10
+ def collect(values)
11
+ ArrayCollection::Collect.new(values)
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ArrayCollection
4
+ # Internal hooks
5
+ module Hooks
6
+ def before(method_to_hook, before_method)
7
+ alias_method(:"#{method_to_hook}_original", method_to_hook)
8
+ define_method(method_to_hook) do |*args, &block|
9
+ send(before_method)
10
+ send(:"#{method_to_hook}_original", *args, &block)
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ArrayCollection
4
+ VERSION = "0.2.7"
5
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "array_collection/version"
4
+ require_relative "array_collection/collect"
5
+ require_relative "array_collection/helper"
6
+
7
+ module ArrayCollection
8
+ class Error < StandardError; end
9
+ end
data/package.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "dependencies": {
3
+ "standard-version": "^9.5.0"
4
+ }
5
+ }
@@ -0,0 +1,4 @@
1
+ module ArrayCollection
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,64 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: array_collection
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.7
5
+ platform: ruby
6
+ authors:
7
+ - Wailan Tirajoh
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-03-26 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Write a longer description or delete this line.
14
+ email:
15
+ - wailantirajoh@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".rspec"
21
+ - ".rubocop.yml"
22
+ - ".ruby-version"
23
+ - ".versionrc.js"
24
+ - CHANGELOG.md
25
+ - CODE_OF_CONDUCT.md
26
+ - LICENSE.txt
27
+ - README.md
28
+ - Rakefile
29
+ - collection.gemspec
30
+ - lib/array_collection.rb
31
+ - lib/array_collection/collect.rb
32
+ - lib/array_collection/collection_array.rb
33
+ - lib/array_collection/collection_filter.rb
34
+ - lib/array_collection/data_accessor.rb
35
+ - lib/array_collection/helper.rb
36
+ - lib/array_collection/hooks.rb
37
+ - lib/array_collection/version.rb
38
+ - package.json
39
+ - sig/collection.rbs
40
+ homepage: https://github.com/WailanTirajoh/ruby_collection
41
+ licenses:
42
+ - MIT
43
+ metadata:
44
+ changelog_uri: https://github.com/WailanTirajoh/ruby_collection/CHANGELOG.md
45
+ post_install_message:
46
+ rdoc_options: []
47
+ require_paths:
48
+ - lib
49
+ required_ruby_version: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: 3.0.0
54
+ required_rubygems_version: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ - - ">="
57
+ - !ruby/object:Gem::Version
58
+ version: '0'
59
+ requirements: []
60
+ rubygems_version: 3.4.10
61
+ signing_key:
62
+ specification_version: 4
63
+ summary: gem for array collection
64
+ test_files: []