hash_helper 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/.rspec +3 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +84 -0
- data/Gemfile +12 -0
- data/LICENSE.txt +21 -0
- data/README.md +126 -0
- data/Rakefile +8 -0
- data/lib/hash_helper/deep_invert.rb +59 -0
- data/lib/hash_helper/deep_normalize.rb +52 -0
- data/lib/hash_helper/deep_sort.rb +45 -0
- data/lib/hash_helper/deep_sum.rb +26 -0
- data/lib/hash_helper/percentage.rb +47 -0
- data/lib/hash_helper/to_nested_h.rb +32 -0
- data/lib/hash_helper/version.rb +5 -0
- data/lib/hash_helper.rb +24 -0
- data/sig/hash_helper.rbs +4 -0
- metadata +82 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: e0460b7d22c2c95b723f38f0ccf08230d10162b2ca9b55f50c84a109fd6991bd
|
4
|
+
data.tar.gz: ff11482c043c447f6c67786e5430188aa3f9c90adaa6ad9b901e3aad860da556
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: de1087e25f9ea6aaa315d7c087683d4e2b8a9d5e4ace4abac428f5f519762a0fb1d55fbe28f763c28420731d880433bb5c885ebfa56d67afb756ef822945130e
|
7
|
+
data.tar.gz: a408206902cfe0c1e56722f6aa7cb3e375531b7f02ebb4814b9af44fe4d37cdba387a59550266dd012fedb9df813d2f63ee000cc5201f7fbae78c76774730e72
|
data/.rspec
ADDED
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -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 tobias.knudsen@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/Gemfile
ADDED
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2024 Tobias Knudsen
|
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,126 @@
|
|
1
|
+
# HashHelper Gem
|
2
|
+
|
3
|
+
`HashHelper` is a versatile Ruby gem providing powerful utility modules for deeply nested hashes. It simplifies common operations such as deep inversion, normalization, summation, percentage calculations, and converting arrays into nested hash structures. This gem automatically extends `Hash` and `Array` with the provided methods, allowing you to seamlessly manipulate nested data.
|
4
|
+
|
5
|
+
## Installation
|
6
|
+
|
7
|
+
Add this line to your application's Gemfile:
|
8
|
+
|
9
|
+
```ruby
|
10
|
+
gem 'hash_helper'
|
11
|
+
```
|
12
|
+
|
13
|
+
And then execute:
|
14
|
+
|
15
|
+
```bash
|
16
|
+
$ bundle install
|
17
|
+
```
|
18
|
+
|
19
|
+
Or install it yourself as:
|
20
|
+
|
21
|
+
```bash
|
22
|
+
$ gem install hash_helper
|
23
|
+
```
|
24
|
+
|
25
|
+
## Features
|
26
|
+
|
27
|
+
### 1. DeepInvert
|
28
|
+
|
29
|
+
Deeply inverts a hash, reversing the nesting structure.
|
30
|
+
|
31
|
+
**Example:**
|
32
|
+
|
33
|
+
```ruby
|
34
|
+
hash = { a: { b: { c: 1 } }, d: { e: 2 } }
|
35
|
+
inverted = hash.deep_invert
|
36
|
+
# Result: { c: { b: { a: 1 } }, e: { d: 2 } }
|
37
|
+
```
|
38
|
+
|
39
|
+
---
|
40
|
+
|
41
|
+
### 2. DeepNormalize
|
42
|
+
|
43
|
+
Recursively normalizes a hash by ensuring all layers in the nested structure contain the same keys, merging it with a default structure to fill in any missing keys or values.
|
44
|
+
|
45
|
+
**Example:**
|
46
|
+
|
47
|
+
```ruby
|
48
|
+
hash = { a: { x: 1, y: 2 }, b: { z: 3 } }
|
49
|
+
normalized = hash.deep_normalize(default_value: 0)
|
50
|
+
# Result: { a: { x: 1, y: 2, z: 0 }, b: { x: 0, y: 0, z: 3 } }
|
51
|
+
```
|
52
|
+
|
53
|
+
---
|
54
|
+
|
55
|
+
### 3. DeepSum
|
56
|
+
|
57
|
+
Calculates the sum of all numeric values in a nested hash or array.
|
58
|
+
|
59
|
+
**Example:**
|
60
|
+
|
61
|
+
```ruby
|
62
|
+
hash = {
|
63
|
+
a: 1,
|
64
|
+
b: { c: 2, d: { e: 3, f: 4 } },
|
65
|
+
g: [5, { h: 6, i: { j: 7 } }]
|
66
|
+
}
|
67
|
+
result = hash.deep_sum
|
68
|
+
# Result: 28
|
69
|
+
```
|
70
|
+
|
71
|
+
---
|
72
|
+
|
73
|
+
### 4. Percentage
|
74
|
+
|
75
|
+
Transforms numeric values in a hash into percentages relative to a layer or the entire structure.
|
76
|
+
|
77
|
+
**Example:**
|
78
|
+
|
79
|
+
```ruby
|
80
|
+
hash = { a: 50, b: { c: 30, d: 20 }, e: 100 }
|
81
|
+
|
82
|
+
# Global percentages
|
83
|
+
percentages = hash.deep_transform_values_to_percentages(relative: false)
|
84
|
+
# Result: { a: 25.0, b: { c: 15.0, d: 10.0 }, e: 50.0 }
|
85
|
+
|
86
|
+
# Relative percentages
|
87
|
+
relative_percentages = hash.deep_transform_values_to_percentages(relative: true)
|
88
|
+
# Result: { a: 25.0, b: { c: 60.0, d: 40.0 }, e: 50.0 }
|
89
|
+
```
|
90
|
+
|
91
|
+
---
|
92
|
+
|
93
|
+
### 5. ToNestedH
|
94
|
+
|
95
|
+
Converts a nested array into a nested hash with a default value at leaf nodes.
|
96
|
+
|
97
|
+
**Example:**
|
98
|
+
|
99
|
+
```ruby
|
100
|
+
nested_array = [[:a, :b], [:x, :y], [:m, :n]]
|
101
|
+
nested_hash = nested_array.to_nested_h(value: "leaf")
|
102
|
+
# Result:
|
103
|
+
# {
|
104
|
+
# a: { x: { m: "leaf", n: "leaf" }, y: { m: "leaf", n: "leaf" } },
|
105
|
+
# b: { x: { m: "leaf", n: "leaf" }, y: { m: "leaf", n: "leaf" } }
|
106
|
+
# }
|
107
|
+
```
|
108
|
+
|
109
|
+
## Usage
|
110
|
+
|
111
|
+
The gem automatically extends `Hash` and `Array` with the provided methods. You can use them directly:
|
112
|
+
|
113
|
+
```ruby
|
114
|
+
require 'hash_helper'
|
115
|
+
|
116
|
+
hash = { a: { b: { c: 1 } } }
|
117
|
+
puts hash.deep_invert
|
118
|
+
```
|
119
|
+
|
120
|
+
## Contributing
|
121
|
+
|
122
|
+
Bug reports and pull requests are welcome on GitHub at [https://github.com/Synsbasen/hash\_helper](https://github.com/Synsbasen/hash_helper).
|
123
|
+
|
124
|
+
## License
|
125
|
+
|
126
|
+
The gem is available as open-source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
data/Rakefile
ADDED
@@ -0,0 +1,59 @@
|
|
1
|
+
module HashHelper
|
2
|
+
module DeepInvert
|
3
|
+
# Deeply inverts a hash, creating a new structure where the values in the original
|
4
|
+
# hash are moved outward, and the keys are reversed in the nesting.
|
5
|
+
#
|
6
|
+
# @return [Hash] A new hash with the keys and values deeply inverted.
|
7
|
+
#
|
8
|
+
# @example Deeply invert a nested hash
|
9
|
+
# hash = { a: { b: { c: 1 } }, d: { e: 2 } }
|
10
|
+
# hash.extend(HashHelper::DeepInvert)
|
11
|
+
# inverted = hash.deep_invert
|
12
|
+
# # Result: { c: { b: { a: 1 } }, e: { d: 2 } }
|
13
|
+
def deep_invert
|
14
|
+
each_with_object({}) do |(outer_key, outer_value), result|
|
15
|
+
traverse_and_invert(outer_value, [outer_key], result)
|
16
|
+
end
|
17
|
+
end
|
18
|
+
|
19
|
+
private
|
20
|
+
|
21
|
+
# Recursively traverses and inverts a nested hash, tracking the full key path.
|
22
|
+
#
|
23
|
+
# This method traverses through the current hash and builds an inverted structure
|
24
|
+
# in the result hash. It uses the key path to reverse the nesting and assign values.
|
25
|
+
#
|
26
|
+
# @param [Hash] current_hash The hash being traversed.
|
27
|
+
# @param [Array] path The path of keys leading to the current value.
|
28
|
+
# @param [Hash] result The hash being built with the inverted structure. def traverse_and_invert(current_hash, path, result)
|
29
|
+
def traverse_and_invert(current_hash, path, result)
|
30
|
+
current_hash.each do |key, value|
|
31
|
+
if value.is_a?(Hash)
|
32
|
+
traverse_and_invert(value, path + [key], result)
|
33
|
+
else
|
34
|
+
insert_inverted_path(result, path + [key], value)
|
35
|
+
end
|
36
|
+
end
|
37
|
+
end
|
38
|
+
|
39
|
+
# Inserts a value into the inverted structure at the specified key path.
|
40
|
+
#
|
41
|
+
# This method traverses the `result` hash using the reversed key path,
|
42
|
+
# creating nested structures as necessary, and assigns the value to the outermost key.
|
43
|
+
#
|
44
|
+
# @param [Hash] result The hash where the inverted structure is being built.
|
45
|
+
# @param [Array] keys The reversed key path to the value.
|
46
|
+
# @param [Object] value The value to assign at the end of the key path.
|
47
|
+
def insert_inverted_path(result, keys, value)
|
48
|
+
current = result
|
49
|
+
|
50
|
+
# Last key (leaf) holds the outer key and value
|
51
|
+
keys[1..-1].reverse.each do |key|
|
52
|
+
current[key] ||= {}
|
53
|
+
current = current[key]
|
54
|
+
end
|
55
|
+
|
56
|
+
current[keys.first] = value
|
57
|
+
end
|
58
|
+
end
|
59
|
+
end
|
@@ -0,0 +1,52 @@
|
|
1
|
+
require "active_support/core_ext/hash/deep_merge"
|
2
|
+
|
3
|
+
module HashHelper
|
4
|
+
module DeepNormalize
|
5
|
+
# Recursively normalizes the hash by merging it with a default structure.
|
6
|
+
#
|
7
|
+
# This method creates a nested default structure based on the keys of the hash,
|
8
|
+
# assigning each key a specified default value. The resulting structure is then
|
9
|
+
# deeply merged with the original hash.
|
10
|
+
#
|
11
|
+
# @param [Object] default_value The value to assign as the default for all keys
|
12
|
+
# in the normalized structure. Defaults to `nil`.
|
13
|
+
# @return [Hash] A new hash that combines the default structure and the original hash.
|
14
|
+
#
|
15
|
+
# @example Normalize a hash with default values
|
16
|
+
# hash = { a: { x: 1, y: 2 }, b: { z: 3 } }
|
17
|
+
# hash.extend(HashHelper::DeepNormalize)
|
18
|
+
# normalized = hash.deep_normalize(default_value: 0)
|
19
|
+
# # Result: { a: { x: 1, y: 2, z: 0 }, b: { x: 0, y: 0, z: 3 } }
|
20
|
+
def deep_normalize(default_value: nil)
|
21
|
+
build_default(self, default_value: default_value).deep_merge(self)
|
22
|
+
end
|
23
|
+
|
24
|
+
private
|
25
|
+
|
26
|
+
# Builds a default hash structure recursively based on the given hash's keys.
|
27
|
+
#
|
28
|
+
# This method traverses the nested structure of the hash, constructing a new
|
29
|
+
# hash where each key is assigned the specified default value. If the original
|
30
|
+
# hash contains nested hashes, the method merges those nested hashes to create
|
31
|
+
# a template for the default structure.
|
32
|
+
#
|
33
|
+
# @param [Hash] obj The hash for which to create a default structure.
|
34
|
+
# @param [Object] default_value The value to assign as the default for all keys
|
35
|
+
# in the default structure. Defaults to `nil`.
|
36
|
+
# @return [Hash] A new hash with the default structure.
|
37
|
+
#
|
38
|
+
# @example Build a default structure
|
39
|
+
# hash = { a: { x: 1, y: 2 }, b: { z: 3 } }
|
40
|
+
# build_default(hash, default_value: 0)
|
41
|
+
# # Result: { a: { x: 0, y: 0, z: 0 }, b: { x: 0, y: 0, z: 0 } }
|
42
|
+
def build_default(obj, default_value: nil)
|
43
|
+
return obj.transform_values { default_value } unless obj.values.first.is_a?(Hash)
|
44
|
+
|
45
|
+
# Merge all nested hashes into a single "template"
|
46
|
+
merged_template = obj.values.reduce(&:deep_merge)
|
47
|
+
|
48
|
+
# Recursively build the default hash for all keys
|
49
|
+
obj.keys.product([build_default(merged_template, default_value: default_value)]).to_h
|
50
|
+
end
|
51
|
+
end
|
52
|
+
end
|
@@ -0,0 +1,45 @@
|
|
1
|
+
module HashHelper
|
2
|
+
module DeepSort
|
3
|
+
# Recursively sorts the hash by keys in lexicographic order.
|
4
|
+
#
|
5
|
+
# @return [Hash] A new hash with keys sorted lexicographically.
|
6
|
+
#
|
7
|
+
# @example Sort a flat hash
|
8
|
+
# { "b" => 1, "a" => 2, "c" => 3 }.deep_sort
|
9
|
+
# # => { "a" => 2, "b" => 1, "c" => 3 }
|
10
|
+
#
|
11
|
+
# @example Sort a nested hash
|
12
|
+
# { "b" => { "d" => 2, "c" => 1 }, "a" => { "e" => 3, "f" => 4 } }.deep_sort
|
13
|
+
# # => { "a" => { "e" => 3, "f" => 4 }, "b" => { "c" => 1, "d" => 2 } }
|
14
|
+
def deep_sort
|
15
|
+
deep_sort_by { |key, _value| key }
|
16
|
+
end
|
17
|
+
|
18
|
+
# Recursively sorts the hash by a custom block.
|
19
|
+
#
|
20
|
+
# @yieldparam [String, Symbol] key The current key being evaluated for sorting.
|
21
|
+
# @yieldparam [Object] value The current value associated with the key.
|
22
|
+
# @return [Hash] A new hash with keys sorted based on the provided block.
|
23
|
+
#
|
24
|
+
# @example Sort by key length
|
25
|
+
# { "apple" => 1, "pear" => 2 }.deep_sort_by { |key, _value| key.length }
|
26
|
+
# # => { "pear" => 2, "apple" => 1 }
|
27
|
+
#
|
28
|
+
# @example Sort by value
|
29
|
+
# { "a" => 3, "b" => 1 }.deep_sort_by { |_key, value| value }
|
30
|
+
# # => { "b" => 1, "a" => 3 }
|
31
|
+
#
|
32
|
+
# @example Place 'null' at the end
|
33
|
+
# { "b" => 1, "a" => 2, "null" => 3 }.deep_sort_by { |key, _value| key == "null" ? 1 : 0 }
|
34
|
+
# # => { "a" => 2, "b" => 1, "null" => 3 }
|
35
|
+
def deep_sort_by(&block)
|
36
|
+
sorted_pairs = sort_by do |key, value|
|
37
|
+
block.call(key, value.is_a?(Hash) ? nil : value)
|
38
|
+
end
|
39
|
+
|
40
|
+
sorted_pairs.each_with_object({}) do |(key, value), result|
|
41
|
+
result[key] = value.is_a?(Hash) ? value.deep_sort_by(&block) : value
|
42
|
+
end
|
43
|
+
end
|
44
|
+
end
|
45
|
+
end
|
@@ -0,0 +1,26 @@
|
|
1
|
+
module HashHelper
|
2
|
+
module DeepSum
|
3
|
+
# This method calculates the sum of all numeric values in a nested Hash or Array.
|
4
|
+
# It recursively traverses the data structure to find and sum up all numbers.
|
5
|
+
#
|
6
|
+
# @example Example with nested hashes and arrays:
|
7
|
+
# hash = {
|
8
|
+
# a: 1,
|
9
|
+
# b: { c: 2, d: { e: 3, f: 4 } },
|
10
|
+
# g: [5, { h: 6, i: { j: 7 } }]
|
11
|
+
# }
|
12
|
+
# hash.deep_sum # => 28
|
13
|
+
def deep_sum
|
14
|
+
sum do |_, value|
|
15
|
+
case value
|
16
|
+
when Hash
|
17
|
+
value.deep_sum
|
18
|
+
when Array
|
19
|
+
value.sum { |v| v.is_a?(Hash) ? v.deep_sum : v.to_f }
|
20
|
+
else
|
21
|
+
value.to_f
|
22
|
+
end
|
23
|
+
end
|
24
|
+
end
|
25
|
+
end
|
26
|
+
end
|
@@ -0,0 +1,47 @@
|
|
1
|
+
require 'active_support/core_ext/hash/deep_transform_values'
|
2
|
+
require_relative "deep_sum"
|
3
|
+
|
4
|
+
module HashHelper
|
5
|
+
module Percentage
|
6
|
+
include HashHelper::DeepSum
|
7
|
+
|
8
|
+
# Transforms all numeric values in the hash into percentages.
|
9
|
+
#
|
10
|
+
# @param [Boolean] relative If `true`, calculates percentages relative to the current layer.
|
11
|
+
# If `false`, calculates percentages relative to the entire hash. Defaults to `true`.
|
12
|
+
# @param [Integer, nil] precision The number of decimal places to round the percentages to. Defaults to no rounding.
|
13
|
+
# @return [Hash] A new hash with numeric values transformed into percentages.
|
14
|
+
#
|
15
|
+
# @example Global percentages (relative: false)
|
16
|
+
# { a: 50, b: { c: 30, d: 20 }, e: 100 }.deep_transform_values_to_percentages
|
17
|
+
# # => { a: 25.0, b: { c: 15.0, d: 10.0 }, e: 50.0 }
|
18
|
+
#
|
19
|
+
# @example Relative percentages for each layer (relative: true)
|
20
|
+
# { a: 50, b: { c: 30, d: 20 }, e: 100 }.deep_transform_values_to_percentages(relative: true)
|
21
|
+
# # => { a: 50.0, b: { c: 60.0, d: 40.0 }, e: 100.0 }
|
22
|
+
def deep_transform_values_to_percentages(relative: true, precision: nil)
|
23
|
+
total_sum = deep_sum
|
24
|
+
|
25
|
+
calculate_percentage = lambda do |value|
|
26
|
+
return value unless value.is_a?(Numeric)
|
27
|
+
return value unless total_sum.positive?
|
28
|
+
|
29
|
+
percentage = (value / total_sum.to_f * 100)
|
30
|
+
precision ? percentage.round(precision) : percentage
|
31
|
+
end
|
32
|
+
|
33
|
+
unless relative
|
34
|
+
return deep_transform_values { |value| calculate_percentage.call(value) }
|
35
|
+
end
|
36
|
+
|
37
|
+
transform_values do |value|
|
38
|
+
case value
|
39
|
+
when Hash
|
40
|
+
value.deep_transform_values_to_percentages(relative: relative, precision: precision)
|
41
|
+
else
|
42
|
+
calculate_percentage.call(value)
|
43
|
+
end
|
44
|
+
end
|
45
|
+
end
|
46
|
+
end
|
47
|
+
end
|
@@ -0,0 +1,32 @@
|
|
1
|
+
module HashHelper
|
2
|
+
module ToNestedH
|
3
|
+
# Converts a nested array into a nested hash with a default value at leaf nodes.
|
4
|
+
# Each array in the input represents a level of keys in the resulting hash.
|
5
|
+
#
|
6
|
+
# @param [Object] value The default value to assign to the leaf nodes (default: nil).
|
7
|
+
# @return [Hash] A nested hash structure with the specified default value at the leaves.
|
8
|
+
#
|
9
|
+
# @example Single level array
|
10
|
+
# [[:a, :b]].to_nested_h
|
11
|
+
# # => {:a => nil, :b => nil}
|
12
|
+
#
|
13
|
+
# @example Two levels of nesting
|
14
|
+
# [[:a, :b], [:x, :y]].to_nested_h(value: 0)
|
15
|
+
# # => {:a => {:x => 0, :y => 0}, :b => {:x => 0, :y => 0}}
|
16
|
+
#
|
17
|
+
# @example Multiple levels of nesting
|
18
|
+
# [[:a, :b], [:x, :y], [:m, :n]].to_nested_h(value: "leaf")
|
19
|
+
# # => {
|
20
|
+
# # :a => { :x => { :m => "leaf", :n => "leaf" }, :y => { :m => "leaf", :n => "leaf" } },
|
21
|
+
# # :b => { :x => { :m => "leaf", :n => "leaf" }, :y => { :m => "leaf", :n => "leaf" } }
|
22
|
+
# # }
|
23
|
+
def to_nested_h(value: nil)
|
24
|
+
return {} if empty?
|
25
|
+
return first.product([value]).to_h if size == 1
|
26
|
+
|
27
|
+
first.map do |key|
|
28
|
+
[key, self[1..].to_nested_h(value: value)]
|
29
|
+
end.to_h
|
30
|
+
end
|
31
|
+
end
|
32
|
+
end
|
data/lib/hash_helper.rb
ADDED
@@ -0,0 +1,24 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "hash_helper/version"
|
4
|
+
require_relative "hash_helper/deep_sum"
|
5
|
+
require_relative "hash_helper/deep_invert"
|
6
|
+
require_relative "hash_helper/deep_normalize"
|
7
|
+
require_relative "hash_helper/percentage"
|
8
|
+
require_relative "hash_helper/to_nested_h"
|
9
|
+
require_relative "hash_helper/deep_sort"
|
10
|
+
|
11
|
+
module HashHelper
|
12
|
+
end
|
13
|
+
|
14
|
+
class Hash
|
15
|
+
include HashHelper::DeepSum
|
16
|
+
include HashHelper::DeepInvert
|
17
|
+
include HashHelper::DeepNormalize
|
18
|
+
include HashHelper::Percentage
|
19
|
+
include HashHelper::DeepSort
|
20
|
+
end
|
21
|
+
|
22
|
+
class Array
|
23
|
+
include HashHelper::ToNestedH
|
24
|
+
end
|
data/sig/hash_helper.rbs
ADDED
metadata
ADDED
@@ -0,0 +1,82 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: hash_helper
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Jimmy Poulsen
|
8
|
+
- Tobias Knudsen
|
9
|
+
autorequire:
|
10
|
+
bindir: exe
|
11
|
+
cert_chain: []
|
12
|
+
date: 2024-12-18 00:00:00.000000000 Z
|
13
|
+
dependencies:
|
14
|
+
- !ruby/object:Gem::Dependency
|
15
|
+
name: activesupport
|
16
|
+
requirement: !ruby/object:Gem::Requirement
|
17
|
+
requirements:
|
18
|
+
- - "~>"
|
19
|
+
- !ruby/object:Gem::Version
|
20
|
+
version: '7.0'
|
21
|
+
type: :runtime
|
22
|
+
prerelease: false
|
23
|
+
version_requirements: !ruby/object:Gem::Requirement
|
24
|
+
requirements:
|
25
|
+
- - "~>"
|
26
|
+
- !ruby/object:Gem::Version
|
27
|
+
version: '7.0'
|
28
|
+
description: HashHelper is a collection of advanced helper methods for Ruby hashes.
|
29
|
+
It provides tools for deep inversion, normalization, percentage calculations, recursive
|
30
|
+
operations, sorting, validation, linear regression, and much more. HashHelper is
|
31
|
+
designed to simplify complex hash manipulations with clean, reusable methods. Extend
|
32
|
+
the power of the Hash class seamlessly!
|
33
|
+
email:
|
34
|
+
- jimmypoulsen96@gmail.com
|
35
|
+
- tobias.knudsen@gmail.com
|
36
|
+
executables: []
|
37
|
+
extensions: []
|
38
|
+
extra_rdoc_files: []
|
39
|
+
files:
|
40
|
+
- ".rspec"
|
41
|
+
- CHANGELOG.md
|
42
|
+
- CODE_OF_CONDUCT.md
|
43
|
+
- Gemfile
|
44
|
+
- LICENSE.txt
|
45
|
+
- README.md
|
46
|
+
- Rakefile
|
47
|
+
- lib/hash_helper.rb
|
48
|
+
- lib/hash_helper/deep_invert.rb
|
49
|
+
- lib/hash_helper/deep_normalize.rb
|
50
|
+
- lib/hash_helper/deep_sort.rb
|
51
|
+
- lib/hash_helper/deep_sum.rb
|
52
|
+
- lib/hash_helper/percentage.rb
|
53
|
+
- lib/hash_helper/to_nested_h.rb
|
54
|
+
- lib/hash_helper/version.rb
|
55
|
+
- sig/hash_helper.rbs
|
56
|
+
homepage: https://github.com/Synsbasen/hash_helper
|
57
|
+
licenses:
|
58
|
+
- MIT
|
59
|
+
metadata:
|
60
|
+
homepage_uri: https://github.com/Synsbasen/hash_helper
|
61
|
+
source_code_uri: https://github.com/Synsbasen/hash_helper
|
62
|
+
changelog_uri: https://github.com/Synsbasen/hash_helper
|
63
|
+
post_install_message:
|
64
|
+
rdoc_options: []
|
65
|
+
require_paths:
|
66
|
+
- lib
|
67
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
68
|
+
requirements:
|
69
|
+
- - ">="
|
70
|
+
- !ruby/object:Gem::Version
|
71
|
+
version: 2.6.0
|
72
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
73
|
+
requirements:
|
74
|
+
- - ">="
|
75
|
+
- !ruby/object:Gem::Version
|
76
|
+
version: '0'
|
77
|
+
requirements: []
|
78
|
+
rubygems_version: 3.4.6
|
79
|
+
signing_key:
|
80
|
+
specification_version: 4
|
81
|
+
summary: Advanced utility methods for working with nested and complex hashes in Ruby.
|
82
|
+
test_files: []
|