Skip to content

Commit

Permalink
Performance and memory improvements (#140)
Browse files Browse the repository at this point in the history
* Use each_with_object instead of Hash[map]

* Mutate new string

* Use curly brackets for new hash

* Use curly brackets for new hash

* Reverse array in-place
  • Loading branch information
krzysiek1507 authored and nesaulov committed May 16, 2019
1 parent 428b440 commit a011a5f
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 12 deletions.
8 changes: 4 additions & 4 deletions lib/surrealist/hash_utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ class << self
#
# @return [Hash] camelized hash.
def camelize_hash(hash)
if hash.is_a?(Hash)
Hash[hash.map { |k, v| [camelize_key(k, false), camelize_hash(v)] }]
else
hash
return hash unless hash.is_a?(Hash)

hash.each_with_object({}) do |(k, v), obj|
obj[camelize_key(k, false)] = camelize_hash(v)
end
end

Expand Down
17 changes: 10 additions & 7 deletions lib/surrealist/string_utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@ class << self
#
# @return [String] new underscored string.
def underscore(string)
string.gsub(NAMESPACES_SEPARATOR, UNDERSCORE)
.gsub(DASH_REGEXP1, UNDERSCORE_SUBSTITUTE)
.gsub(DASH_REGEXP2, UNDERSCORE_SUBSTITUTE)
.tr(DASH, UNDERSCORE)
.downcase
dup = string.gsub(NAMESPACES_SEPARATOR, UNDERSCORE)
dup.gsub!(DASH_REGEXP1, UNDERSCORE_SUBSTITUTE)
dup.gsub!(DASH_REGEXP2, UNDERSCORE_SUBSTITUTE)
dup.tr!(DASH, UNDERSCORE)
dup.downcase!
dup
end

# Camelizes a string.
Expand Down Expand Up @@ -71,8 +72,10 @@ def extract_class(string)
def break_namespaces(klass, camelize, nesting_level)
Surrealist::ExceptionRaiser.raise_invalid_nesting!(nesting_level) unless nesting_level.positive?

klass.split(NAMESPACES_SEPARATOR).last(nesting_level).reverse.inject({}) do |a, n|
camelize ? Hash[camelize(uncapitalize(n), false).to_sym => a] : Hash[underscore(n).to_sym => a]
klass.split(NAMESPACES_SEPARATOR).last(nesting_level).reverse!.inject({}) do |a, n|
key = (camelize ? camelize(uncapitalize(n), false) : underscore(n)).to_sym

{ key => a }
end
end

Expand Down
2 changes: 1 addition & 1 deletion lib/surrealist/wrapper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def wrap_schema_into_root(schema, carrier, root)
else
Surrealist::StringUtils.underscore(root).to_sym
end
result = Hash[root_key => {}]
result = { root_key => {} }
Surrealist::Copier.deep_copy(schema, result[root_key])

result
Expand Down

0 comments on commit a011a5f

Please sign in to comment.