Skip to content

Commit ae259e9

Browse files
committed
Decrease complexity of vendored_packages_without_version method
It was O(n^2) because it iterated over packages_with_versions multiple times. Now it is O(n) because it uses a set to track versioned packages and checks membership in constant time. Also do a single pass in the importmap lines to find unversioned packages.
1 parent 14068d4 commit ae259e9

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

lib/importmap/npm.rb

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -139,17 +139,25 @@ def post_json(uri, body)
139139
end
140140

141141
def vendored_packages_without_version(packages_with_versions)
142+
versioned_packages = packages_with_versions.map(&:first).to_set
143+
142144
importmap
143145
.lines
144-
.filter_map do |line|
145-
next line.match(/#{PIN_REGEX}to: ["']([^["']]*)["'].*/).captures if line.include?("to:")
146-
match = line.match(PIN_REGEX)
147-
[match.captures.first, "#{match.captures.first}.js"] if match
148-
end
149-
.filter_map do |package, filename|
150-
next if packages_with_versions.map(&:first).include?(package)
151-
path = File.join(@vendor_path, filename)
152-
[package, path] if File.exist?(path)
153-
end
146+
.filter_map { |line| find_unversioned_vendored_package(line, versioned_packages) }
147+
end
148+
149+
def find_unversioned_vendored_package(line, versioned_packages)
150+
regexp = line.include?("to:")? /#{PIN_REGEX}to: ["']([^["']]*)["'].*/ : PIN_REGEX
151+
match = line.match(regexp)
152+
153+
return unless match
154+
155+
package, filename = match.captures
156+
filename ||= "#{package}.js"
157+
158+
return if versioned_packages.include?(package)
159+
160+
path = File.join(@vendor_path, filename)
161+
[package, path] if File.exist?(path)
154162
end
155163
end

0 commit comments

Comments
 (0)