enum_utils 0.1.0

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: 5fa25b37c2507249c0fdc58bc3217845ef9e48540870a0bdcc8039b841197e24
4
+ data.tar.gz: 2feb7bf6b2885e4de8d7c9d3581e16bb0371db974da4862059a218fd994d4f91
5
+ SHA512:
6
+ metadata.gz: 5892a6f88b623cdd2fc9d09806a54eedddda69522853849c87e58b57ede91babc71962d2341febb47fda25421c957e367658de4ccce61d7cabdc99a9c9b9b81e
7
+ data.tar.gz: 78ce23e6434dba7082f131d7a45f616327fd865eb16f5c0893fe4a673af02d8679b99feaa207be0e03047e750fdf5f8ba38e89c0a196114e0736acd38ca9b628
@@ -0,0 +1,30 @@
1
+ name: Ruby
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ pull_request:
9
+
10
+ jobs:
11
+ build:
12
+ runs-on: ubuntu-latest
13
+ name: Ruby ${{ matrix.ruby }}
14
+ strategy:
15
+ matrix:
16
+ ruby:
17
+ - '2.6.9'
18
+ - '2.7.5'
19
+ - '3.0.3'
20
+ - '3.1.1'
21
+
22
+ steps:
23
+ - uses: actions/checkout@v2
24
+ - name: Set up Ruby
25
+ uses: ruby/setup-ruby@v1
26
+ with:
27
+ ruby-version: ${{ matrix.ruby }}
28
+ bundler-cache: true
29
+ - name: Run the default task
30
+ run: bundle exec rake
data/.gitignore ADDED
@@ -0,0 +1,8 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2022-03-04
4
+
5
+ - 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 max@bitsonnet.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/Gemfile ADDED
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ gemspec
6
+
7
+ gem 'rake', '~> 13.0'
8
+ gem 'minitest', '~> 5.0'
9
+ gem 'pry'
data/Gemfile.lock ADDED
@@ -0,0 +1,27 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ enum_utils (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ coderay (1.1.3)
10
+ method_source (1.0.0)
11
+ minitest (5.15.0)
12
+ pry (0.14.1)
13
+ coderay (~> 1.1)
14
+ method_source (~> 1.0)
15
+ rake (13.0.6)
16
+
17
+ PLATFORMS
18
+ ruby
19
+
20
+ DEPENDENCIES
21
+ enum_utils!
22
+ minitest (~> 5.0)
23
+ pry
24
+ rake (~> 13.0)
25
+
26
+ BUNDLED WITH
27
+ 2.3.8
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Max Chernyak
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,171 @@
1
+ # EnumUtils
2
+
3
+ Functions for mixing and matching lazy, potentially infinite enumerables.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'enum_utils'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install enum_utils
20
+
21
+ ## Usage
22
+
23
+ ### EnumUtils.sorted_intersection
24
+
25
+ Given N consistently-sorted enums, return unique values that appear in at least
26
+ [degree] number of different enums, preserving the global order, until all enums
27
+ are depleted. By default a value must appear in all of them.
28
+
29
+ ```ruby
30
+ # 3 ascending enums
31
+ EnumUtils.sorted_intersection(
32
+ [1,2].each,
33
+ [2,3].each,
34
+ [1,2,5].each
35
+ ).to_a # => [2]
36
+
37
+ # 3 descending enums
38
+ EnumUtils.sorted_intersection(
39
+ [2,1].each,
40
+ [3,2].each,
41
+ [5,2,1].each,
42
+ compare: -> a, b { b <=> a } # reverse order comparison
43
+ ).to_a # => [2]
44
+
45
+ # 3 ascending enums with degree 2
46
+ EnumUtils.sorted_intersection(
47
+ [1,2].each,
48
+ [2,3].each,
49
+ [1,2,5].each,
50
+ degree: 2
51
+ ).to_a # => [1, 2]
52
+ ```
53
+
54
+ ### EnumUtils.sorted_union
55
+
56
+ Given N consistently-sorted enums, return all their unique values while
57
+ preserving their global order. If `with_index: true` is given, also return index
58
+ of the enum in which the corresponding value was first seen.
59
+
60
+ ```ruby
61
+ # 3 ascending enums
62
+ EnumUtils.sorted_union(
63
+ [1,2].each,
64
+ [2,3].each,
65
+ [1,2,5].each
66
+ ).to_a # => [1,2,3,5]
67
+
68
+ # 3 descending enums
69
+ EnumUtils.sorted_union(
70
+ [2,1].each,
71
+ [3,2].each,
72
+ [5,2,1].each,
73
+ compare: -> a, b { b <=> a } # reverse order comparison
74
+ ).to_a # => [5,3,2,1]
75
+
76
+ # 3 ascending enums with index
77
+ EnumUtils.sorted_union(
78
+ [1,2].each,
79
+ [2,3].each,
80
+ [1,2,5].each,
81
+ with_index: true
82
+ ).to_a # => [[1,0], [2,0], [3,1], [5,2]]
83
+ ```
84
+
85
+ ### EnumUtils.sorted_merge
86
+
87
+ Given N consistently-sorted enums, return all their values while preserving the
88
+ global order. If `with_index: true` is given, also return index in the enum that
89
+ originated the value.
90
+
91
+ ```ruby
92
+ ## 3 ascending enums
93
+ EnumUtils.sorted_merge(
94
+ [1,2].each,
95
+ [2,3].each,
96
+ [1,2,5].each
97
+ ).to_a # => [1,1,2,2,2,3,5]
98
+
99
+ ## 3 descending enums
100
+ EnumUtils.sorted_merge(
101
+ [2,1].each,
102
+ [3,2].each,
103
+ [5,2,1].each,
104
+ compare: -> a, b { b <=> a } # reverse order comparison
105
+ ).to_a # => [5,3,2,2,2,1,1]
106
+
107
+ ## 3 ascending enums with index
108
+ EnumUtils.sorted_union(
109
+ [1,2].each,
110
+ [2,3].each,
111
+ [1,2,5].each,
112
+ with_index: true
113
+ ).to_a # => [[1,0], [1,2], [2,0], [2,1], [2,2], [3,1], [5,2]]
114
+ ```
115
+
116
+ ### EnumUtils.round_robin
117
+
118
+ Given N enums, return all their values by taking one value from each enum in
119
+ turn, until all are exhausted. If `with_index: true` is given, also return index
120
+ of the enum that originated the value.
121
+
122
+ ```ruby
123
+ ## 3 enums
124
+ EnumUtils.round_robin(
125
+ [3,2].each,
126
+ [1,3].each,
127
+ [5,3,4].each
128
+ ).to_a # => [3,1,5,2,3,3,4]
129
+
130
+ ## 3 enums with index
131
+ EnumUtils.round_robin(
132
+ [3,2].each,
133
+ [1,3].each,
134
+ [5,3,4].each,
135
+ with_index: true
136
+ ).to_a # => [[3,0], [1,1], [5,2], [2,0], [3,1], [3,2], [4,2]]
137
+ ```
138
+
139
+ ### EnumUtils.concat
140
+
141
+ Given N enums, return a new enum which lazily exhausts every enum.
142
+
143
+ ## Development
144
+
145
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run
146
+ `rake test` to run the tests. You can also run `bin/console` for an interactive
147
+ prompt that will allow you to experiment.
148
+
149
+ To install this gem onto your local machine, run `bundle exec rake install`. To
150
+ release a new version, update the version number in `version.rb`, and then run
151
+ `bundle exec rake release`, which will create a git tag for the version, push
152
+ git commits and the created tag, and push the `.gem` file to
153
+ [rubygems.org](https://rubygems.org).
154
+
155
+ ## Contributing
156
+
157
+ Bug reports and pull requests are welcome on GitHub at
158
+ https://github.com/maxim/enum_utils. This project is intended to be a safe,
159
+ welcoming space for collaboration, and contributors are expected to adhere to
160
+ the [code of
161
+ conduct](https://github.com/maxim/enum_utils/blob/master/CODE_OF_CONDUCT.md).
162
+
163
+ ## License
164
+
165
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
166
+
167
+ ## Code of Conduct
168
+
169
+ Everyone interacting in the EnumUtils project's codebases, issue trackers, chat
170
+ rooms and mailing lists is expected to follow the [code of
171
+ conduct](https://github.com/maxim/enum_utils/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rake/testtask'
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << 'test'
8
+ t.libs << 'lib'
9
+ t.test_files = FileList['test/**/*_test.rb']
10
+ end
11
+
12
+ task default: :test
data/bin/console ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'enum_utils'
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ require 'pry'
11
+ Pry.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/enum_utils/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'enum_utils'
7
+ spec.version = EnumUtils::VERSION
8
+ spec.authors = ['Max Chernyak']
9
+ spec.email = ['hello@max.engineer']
10
+
11
+ spec.summary = 'Write a short summary, because RubyGems requires one.'
12
+ spec.description = 'Write a longer description or delete this line.'
13
+ spec.homepage = 'https://github.com/maxim/enum_utils'
14
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.6.9')
15
+
16
+ spec.metadata['allowed_push_host'] = 'https://rubygems.org'
17
+
18
+ spec.metadata['homepage_uri'] = spec.homepage
19
+ spec.metadata['source_code_uri'] = spec.homepage
20
+ spec.metadata['changelog_uri'] = "#{spec.homepage}/blob/main/CHANGELOG.md"
21
+
22
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
23
+ `git ls-files -z`.split("\x0").reject { |f| f.match(/\Atest\//) }
24
+ end
25
+
26
+ spec.require_paths = ['lib']
27
+ end
@@ -0,0 +1,21 @@
1
+ module EnumUtils
2
+ # This is an enumerator wrapper that always caches 1 item in its buffer, and
3
+ # provides the ability to check if underlying enumerator is exhausted.
4
+ class ExhaustibleIter
5
+ EXHAUSTED = Object.new
6
+
7
+ attr_reader :buff_value
8
+
9
+ def initialize(source); @source = source; pull end
10
+ def exhausted?; @buff_value == EXHAUSTED end
11
+ def next; @buff_value.tap { pull } end
12
+
13
+ private
14
+
15
+ def pull
16
+ @buff_value = @source.next
17
+ rescue StopIteration
18
+ @buff_value = EXHAUSTED
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EnumUtils
4
+ VERSION = '0.1.0'
5
+ end
data/lib/enum_utils.rb ADDED
@@ -0,0 +1,269 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'set'
4
+ require_relative 'enum_utils/version'
5
+ require_relative 'enum_utils/exhaustible_iter'
6
+
7
+ module EnumUtils
8
+ extend self
9
+
10
+ # Given N consistently-sorted enums, return unique values that appear in at
11
+ # least [degree] number of different enums, preserving the global order, until
12
+ # all enums are depleted. By default a value must appear in all of them.
13
+ #
14
+ # Examples:
15
+ #
16
+ # ## 3 ascending enums:
17
+ #
18
+ # EnumUtils.sorted_intersection(
19
+ # [1,2].each,
20
+ # [2,3].each,
21
+ # [1,2,5].each
22
+ # ).to_a # => [2]
23
+ #
24
+ # ## 3 descending enums:
25
+ #
26
+ # EnumUtils.sorted_intersection(
27
+ # [2,1].each,
28
+ # [3,2].each,
29
+ # [5,2,1].each,
30
+ # compare: -> a, b { b <=> a } # reverse order comparison
31
+ # ).to_a # => [2]
32
+ #
33
+ # ## 3 ascending enums with degree 2:
34
+ #
35
+ # EnumUtils.sorted_intersection(
36
+ # [1,2].each,
37
+ # [2,3].each,
38
+ # [1,2,5].each,
39
+ # degree: 2
40
+ # ).to_a # => [1, 2]
41
+ def sorted_intersection *enums,
42
+ compare: -> a, b { a <=> b },
43
+ degree: enums.size
44
+
45
+ unless block_given?
46
+ return enum_for(__method__, *enums, compare: compare, degree: degree)
47
+ end
48
+
49
+ active = prepare_enums(enums)
50
+ compare = compare_with_error_handling(compare)
51
+ last_v = []
52
+ seen_i = Set[]
53
+
54
+ while active.size >= (degree - seen_i.size)
55
+ (min_iter, min_iter_i), pos = pick_min(active, compare, demote: seen_i)
56
+ value = min_iter.next
57
+
58
+ if last_v.empty? || compare.(last_v[0], value) != 0
59
+ last_v.replace [value]
60
+ seen_i.replace [min_iter_i]
61
+ else
62
+ seen_i << min_iter_i
63
+ end
64
+
65
+ if seen_i.size == degree
66
+ yield(value)
67
+ last_v.replace []
68
+ seen_i.replace []
69
+ end
70
+
71
+ active.delete_at(pos) if min_iter.exhausted?
72
+ end
73
+ end
74
+
75
+ # Given N consistently-sorted enums, return all their unique values while
76
+ # preserving their global order. If `with_index: true` is given, also return
77
+ # index of the enum in which the corresponding value was first seen.
78
+ #
79
+ # Examples:
80
+ #
81
+ # ## 3 ascending enums:
82
+ #
83
+ # EnumUtils.sorted_union(
84
+ # [1,2].each,
85
+ # [2,3].each,
86
+ # [1,2,5].each
87
+ # ).to_a # => [1,2,3,5]
88
+ #
89
+ # ## 3 descending enums:
90
+ #
91
+ # EnumUtils.sorted_union(
92
+ # [2,1].each,
93
+ # [3,2].each,
94
+ # [5,2,1].each,
95
+ # compare: -> a, b { b <=> a } # reverse order comparison
96
+ # ).to_a # => [5,3,2,1]
97
+ #
98
+ # ## 3 ascending enums with index:
99
+ #
100
+ # EnumUtils.sorted_union(
101
+ # [1,2].each,
102
+ # [2,3].each,
103
+ # [1,2,5].each,
104
+ # with_index: true
105
+ # ).to_a # => [[1,0], [2,0], [3,1], [5,2]]
106
+ def sorted_union(*enums, compare: -> a, b { a <=> b }, with_index: false)
107
+ unless block_given?
108
+ return \
109
+ enum_for(__method__, *enums, compare: compare, with_index: with_index)
110
+ end
111
+
112
+ unless with_index
113
+ return sorted_union(*enums, compare: compare, with_index: true) { |v, _|
114
+ yield v
115
+ }
116
+ end
117
+
118
+ last_v = []
119
+
120
+ sorted_merge(*enums, compare: compare, with_index: with_index).each { |v, i|
121
+ if last_v.empty? || v != last_v[0]
122
+ yield(v, i)
123
+ last_v.replace([v])
124
+ end
125
+ }
126
+ end
127
+
128
+ # Given N consistently-sorted enums, return all their values while preserving
129
+ # the global order. If `with_index: true` is given, also return index in the
130
+ # enum that originated the value.
131
+ #
132
+ # Examples:
133
+ #
134
+ # ## 3 ascending enums:
135
+ #
136
+ # EnumUtils.sorted_merge(
137
+ # [1,2].each,
138
+ # [2,3].each,
139
+ # [1,2,5].each
140
+ # ).to_a # => [1,1,2,2,2,3,5]
141
+ #
142
+ # ## 3 descending enums:
143
+ #
144
+ # EnumUtils.sorted_merge(
145
+ # [2,1].each,
146
+ # [3,2].each,
147
+ # [5,2,1].each,
148
+ # compare: -> a, b { b <=> a } # reverse order comparison
149
+ # ).to_a # => [5,3,2,2,2,1,1]
150
+ #
151
+ # ## 3 ascending enums with index:
152
+ #
153
+ # EnumUtils.sorted_union(
154
+ # [1,2].each,
155
+ # [2,3].each,
156
+ # [1,2,5].each,
157
+ # with_index: true
158
+ # ).to_a # => [[1,0], [1,2], [2,0], [2,1], [2,2], [3,1], [5,2]]
159
+ def sorted_merge(*enums, compare: -> a, b { a <=> b }, with_index: false)
160
+ unless block_given?
161
+ return \
162
+ enum_for(__method__, *enums, compare: compare, with_index: with_index)
163
+ end
164
+
165
+ unless with_index
166
+ return sorted_merge(*enums, compare: compare, with_index: true) { |v, _|
167
+ yield v
168
+ }
169
+ end
170
+
171
+ active = prepare_enums(enums)
172
+ compare = compare_with_error_handling(compare)
173
+
174
+ while active.any?
175
+ (min_iter, min_iter_i), pos = pick_min(active, compare)
176
+ yield(min_iter.next, min_iter_i)
177
+ active.delete_at(pos) if min_iter.exhausted?
178
+ end
179
+ end
180
+
181
+ # Given N enums, return all their values by taking one value from each enum in
182
+ # turn, until all are exhausted. If `with_index: true` is given, also return
183
+ # index of the enum that originated the value.
184
+ #
185
+ # Examples:
186
+ #
187
+ # ## 3 enums:
188
+ #
189
+ # EnumUtils.round_robin(
190
+ # [3,2].each,
191
+ # [1,3].each,
192
+ # [5,3,4].each
193
+ # ).to_a # => [3,1,5,2,3,3,4]
194
+ #
195
+ # ## 3 enums with index:
196
+ #
197
+ # EnumUtils.round_robin(
198
+ # [3,2].each,
199
+ # [1,3].each,
200
+ # [5,3,4].each,
201
+ # with_index: true
202
+ # ).to_a # => [[3,0], [1,1], [5,2], [2,0], [3,1], [3,2], [4,2]]
203
+ def round_robin(*enums, with_index: false)
204
+ unless block_given?
205
+ return enum_for(__method__, *enums, with_index: with_index)
206
+ end
207
+
208
+ unless with_index
209
+ return round_robin(*enums, with_index: true) { |v, _| yield v }
210
+ end
211
+
212
+ active = prepare_enums(enums)
213
+
214
+ while active.any?
215
+ pos = 0
216
+
217
+ while pos < active.size
218
+ iter, i = active[pos]
219
+ yield(iter.next, i)
220
+ iter.exhausted? ? active.delete_at(pos) : pos += 1
221
+ end
222
+ end
223
+ end
224
+
225
+ # Given N enums, return a new enum which lazily exhausts every enum.
226
+ def concat(*enums)
227
+ return enum_for(__method__, *enums) unless block_given?
228
+
229
+ enums
230
+ .lazy
231
+ .flat_map(&:lazy)
232
+ .to_enum { enums.sum(&:size) if enums.all?(&:size) }.each do |v|
233
+ yield(v)
234
+ end
235
+ end
236
+
237
+ private
238
+
239
+ def pick_min(indexed_enums, compare, demote: Set[])
240
+ indexed_enums.each.with_index.min { |((a_enum, ai), _), ((b_enum, bi), _)|
241
+ result = compare.(a_enum.buff_value, b_enum.buff_value)
242
+
243
+ if result.nonzero?
244
+ result
245
+ elsif demote.include?(bi)
246
+ -1
247
+ elsif demote.include?(ai)
248
+ 1
249
+ else
250
+ result
251
+ end
252
+ }
253
+ end
254
+
255
+ def compare_with_error_handling(compare)
256
+ -> a, b {
257
+ result = compare.(a, b)
258
+ return result unless result.nil?
259
+ raise ArgumentError, "comparison of #{a.class} with #{b.class} failed"
260
+ }
261
+ end
262
+
263
+ def prepare_enums(enums)
264
+ enums
265
+ .map
266
+ .with_index { |e, i| [ExhaustibleIter.new(e), i] }
267
+ .reject { |e, _| e.exhausted? }
268
+ end
269
+ end
metadata ADDED
@@ -0,0 +1,61 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: enum_utils
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Max Chernyak
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2022-03-04 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Write a longer description or delete this line.
14
+ email:
15
+ - hello@max.engineer
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".github/workflows/main.yml"
21
+ - ".gitignore"
22
+ - CHANGELOG.md
23
+ - CODE_OF_CONDUCT.md
24
+ - Gemfile
25
+ - Gemfile.lock
26
+ - LICENSE.txt
27
+ - README.md
28
+ - Rakefile
29
+ - bin/console
30
+ - bin/setup
31
+ - enum_utils.gemspec
32
+ - lib/enum_utils.rb
33
+ - lib/enum_utils/exhaustible_iter.rb
34
+ - lib/enum_utils/version.rb
35
+ homepage: https://github.com/maxim/enum_utils
36
+ licenses: []
37
+ metadata:
38
+ allowed_push_host: https://rubygems.org
39
+ homepage_uri: https://github.com/maxim/enum_utils
40
+ source_code_uri: https://github.com/maxim/enum_utils
41
+ changelog_uri: https://github.com/maxim/enum_utils/blob/main/CHANGELOG.md
42
+ post_install_message:
43
+ rdoc_options: []
44
+ require_paths:
45
+ - lib
46
+ required_ruby_version: !ruby/object:Gem::Requirement
47
+ requirements:
48
+ - - ">="
49
+ - !ruby/object:Gem::Version
50
+ version: 2.6.9
51
+ required_rubygems_version: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - ">="
54
+ - !ruby/object:Gem::Version
55
+ version: '0'
56
+ requirements: []
57
+ rubygems_version: 3.3.7
58
+ signing_key:
59
+ specification_version: 4
60
+ summary: Write a short summary, because RubyGems requires one.
61
+ test_files: []