RuboCop: Performance/Sum

[skip-stages=Flakey]

the form .map { }.sum was autocorrected to .sum {}.

.map {}.inject(:+) and variations was manually corrected

Change-Id: I44b8ef3b8257e8acf70f259aed35f1e16cde9856
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/278335
Tested-by: Service Cloud Jenkins <svc.cloudjenkins@instructure.com>
Reviewed-by: Simon Williams <simon@instructure.com>
QA-Review: Cody Cutrer <cody@instructure.com>
Product-Review: Cody Cutrer <cody@instructure.com>
This commit is contained in:
Cody Cutrer 2021-11-15 14:37:45 -07:00
parent 196d92d5d3
commit 14ee01c805
19 changed files with 24 additions and 23 deletions

View File

@ -96,6 +96,8 @@ Performance/StringInclude:
Severity: error Severity: error
Performance/StringReplacement: Performance/StringReplacement:
Severity: error Severity: error
Performance/Sum:
Severity: error
Performance/TimesMap: Performance/TimesMap:
Severity: error Severity: error

View File

@ -140,7 +140,7 @@ module ConditionalRelease
new_scores = Array.wrap(new_score_or_scores).compact new_scores = Array.wrap(new_score_or_scores).compact
return unless old_score && new_scores.present? return unless old_score && new_scores.present?
average = new_scores.reduce(&:+) / new_scores.length average = new_scores.sum / new_scores.length
percentage_points_improvement = average - old_score percentage_points_improvement = average - old_score
return 1 if percentage_points_improvement >= 0.03 return 1 if percentage_points_improvement >= 0.03
return -1 if percentage_points_improvement <= -0.03 return -1 if percentage_points_improvement <= -0.03

View File

@ -474,7 +474,7 @@ class GroupCategory < ActiveRecord::Base
counts = User.joins(:not_ended_enrollments) counts = User.joins(:not_ended_enrollments)
.where(enrollments: { course_id: context, type: 'StudentEnrollment' }) .where(enrollments: { course_id: context, type: 'StudentEnrollment' })
.distinct('user_id').group('course_section_id').count .distinct('user_id').group('course_section_id').count
@create_group_count = counts.values.map { |count| count / @create_group_member_count.to_f }.map(&:ceil).sum @create_group_count = counts.values.map { |count| count / @create_group_member_count.to_f }.sum(&:ceil)
else else
(unassigned_users.to_a.length.to_f / @create_group_member_count).ceil (unassigned_users.to_a.length.to_f / @create_group_member_count).ceil
end end
@ -660,7 +660,7 @@ class GroupCategory < ActiveRecord::Base
end end
@group_distributions[section_id] = dist @group_distributions[section_id] = dist
end end
if @group_distributions.values.map(&:count).sum != @groups.count || @group_distributions.any? { |k, v| v.sum != user_counts[k] } if @group_distributions.values.sum(&:count) != @groups.count || @group_distributions.any? { |k, v| v.sum != user_counts[k] }
raise "user/group count mismatch" # we should make sure this works before going any further raise "user/group count mismatch" # we should make sure this works before going any further
end end

View File

@ -227,7 +227,7 @@ class MediaObject < ActiveRecord::Base
self.max_size = [self.max_size || 0, asset[:size].to_i].max self.max_size = [self.max_size || 0, asset[:size].to_i].max
end end
end end
self.total_size = [self.max_size || 0, assets.map { |a| (a[:size] || 0).to_i }.sum].max self.total_size = [self.max_size || 0, assets.sum { |a| (a[:size] || 0).to_i }].max
self.save self.save
ensure_attachment ensure_attachment
self.data self.data

View File

@ -121,8 +121,7 @@ module Quizzes
end end
result.possible = cached_questions_and_answers.map(&:first) result.possible = cached_questions_and_answers.map(&:first)
.map { |h| h['points_possible'] } .sum { |h| h['points_possible'] }
.inject(:+)
# do not create a result if no points are possible. # do not create a result if no points are possible.
if result.possible == 0 if result.possible == 0
@ -132,8 +131,7 @@ module Quizzes
end end
result.score = cached_questions_and_answers.map(&:last) result.score = cached_questions_and_answers.map(&:last)
.map { |h| h[:points] } .sum { |h| h[:points] }
.inject(:+)
result.calculate_percent! result.calculate_percent!
result.mastery = determine_mastery(result, alignment) result.mastery = determine_mastery(result, alignment)

View File

@ -43,7 +43,7 @@ class Quizzes::QuizRegrader::Submission
def rescored_submission def rescored_submission
previous_score = submission.score_before_regrade || submission.score previous_score = submission.score_before_regrade || submission.score
submission.score += answers_to_grade.map(&:regrade!).inject(&:+) || 0 submission.score += answers_to_grade.sum(&:regrade!)
submission.score_before_regrade = previous_score submission.score_before_regrade = previous_score
submission.quiz_data = regraded_question_data submission.quiz_data = regraded_question_data
submission submission

View File

@ -115,7 +115,7 @@ class Quizzes::QuizStatistics::ItemAnalysis::Summary
size = items.size size = items.size
if size > 1 && variance != 0 if size > 1 && variance != 0
variance_sum = items.map(&:variance).sum variance_sum = items.sum(&:variance)
size / (size - 1.0) * (1 - (variance_sum / variance)) size / (size - 1.0) * (1 - (variance_sum / variance))
else else
nil nil

View File

@ -420,7 +420,7 @@ class Quizzes::QuizStatistics::StudentAnalysis < Quizzes::QuizStatistics::Report
question = Quizzes::QuizQuestion::Base.from_question_data(question).stats(responses) question = Quizzes::QuizQuestion::Base.from_question_data(question).stats(responses)
none = { none = {
:responses => question[:responses] - question[:answers].map { |a| a[:responses] || 0 }.sum, :responses => question[:responses] - question[:answers].sum { |a| a[:responses] || 0 },
:id => "none", :id => "none",
:weight => 0, :weight => 0,
:text => I18n.t('statistics.no_answer', "No Answer"), :text => I18n.t('statistics.no_answer', "No Answer"),

View File

@ -401,7 +401,7 @@ class Rubric < ActiveRecord::Base
end end
def total_points_from_criteria(criteria) def total_points_from_criteria(criteria)
criteria.reject { |c| c[:ignore_for_scoring] }.map { |c| c[:points] }.reduce(:+) criteria.reject { |c| c[:ignore_for_scoring] }.sum { |c| c[:points] }
end end
# undo innocuous changes introduced by migrations which break `will_change_with_update?` # undo innocuous changes introduced by migrations which break `will_change_with_update?`

View File

@ -24,7 +24,7 @@ module Multipart
end end
def size def size
@streams.map(&:size).sum @streams.sum(&:size)
end end
def read(size = nil, outbuf = +"") def read(size = nil, outbuf = +"")

View File

@ -136,7 +136,7 @@ class ScoreStatisticsGenerator
return return
end end
average = current_scores.map(&:to_d).sum / BigDecimal(score_count) average = current_scores.sum(&:to_d) / BigDecimal(score_count)
# This is a safeguard to avoid blowing up due to database storage which is set to be a decimal with a precision of 8 # This is a safeguard to avoid blowing up due to database storage which is set to be a decimal with a precision of 8
# and a scale of 2. And really, what are you even doing awarding 1,000,000% or over in a course? # and a scale of 2. And really, what are you even doing awarding 1,000,000% or over in a course?

View File

@ -23,7 +23,7 @@ module SimpleStats
divisor = type == :population ? items.length : items.length - 1 divisor = type == :population ? items.length : items.length - 1
mean = items.sum / items.length.to_f mean = items.sum / items.length.to_f
sum = items.map { |item| (item - mean)**2 }.sum sum = items.sum { |item| (item - mean)**2 }
(sum / divisor).to_f (sum / divisor).to_f
end end
module_function :variance module_function :variance

View File

@ -211,7 +211,7 @@ module SIS
def update_progress def update_progress
completed_count = @batch.parallel_importers.where(workflow_state: "completed").count completed_count = @batch.parallel_importers.where(workflow_state: "completed").count
current_progress = [(completed_count.to_f * 100 / @parallel_importers.values.map(&:count).sum).round, 99].min current_progress = [(completed_count.to_f * 100 / @parallel_importers.values.sum(&:count)).round, 99].min
SisBatch.where(:id => @batch).where("progress IS NULL or progress < ?", current_progress).update_all(progress: current_progress) SisBatch.where(:id => @batch).where("progress IS NULL or progress < ?", current_progress).update_all(progress: current_progress)
end end
@ -321,7 +321,7 @@ module SIS
end end
end end
@parallel_importers.each do |type, importers| @parallel_importers.each do |type, importers|
@batch.data[:counts][type.to_s.pluralize.to_sym] = importers.map(&:rows_processed).sum @batch.data[:counts][type.to_s.pluralize.to_sym] = importers.sum(&:rows_processed)
end end
finish finish
end end

View File

@ -81,7 +81,7 @@ unless $canvas_tasks_loaded
end end
end end
combined_time = batch_times.reduce(:+) combined_time = batch_times.sum
puts( puts(
"Finished compiling assets in #{real_time.round(2)}s. " + "Finished compiling assets in #{real_time.round(2)}s. " +

View File

@ -38,7 +38,8 @@ describe 'FixPointsPossibleSumsInQuizzes' do
before do before do
# creates rounding error just like the real thing! # creates rounding error just like the real thing!
points = Array.new(question_count) { question_points }.inject(:+) # .sum uses the native ruby 2.4 sum if the first element is numeric in rails 5.1 ...and doesn't quite give the same answer :/ # .sum uses the native ruby 2.4 sum if the first element is numeric in rails 5.1 ...and doesn't quite give the same answer :/
points = Array.new(question_count) { question_points }.inject(:+) # rubocop:disable Performance/Sum
allow(Quizzes::Quiz).to receive(:count_points_possible).and_return(points) allow(Quizzes::Quiz).to receive(:count_points_possible).and_return(points)
end end

View File

@ -727,7 +727,7 @@ def assert_random_group_assignment(category, course, initial_spread, result_spre
end end
# set up course users # set up course users
user_count = result_spread.inject(:+) + expected_leftover_count user_count = result_spread.sum + expected_leftover_count
course_users = create_users_in_course(course, user_count, return_type: :record) course_users = create_users_in_course(course, user_count, return_type: :record)
# set up initial spread # set up initial spread

View File

@ -48,7 +48,7 @@ describe Quizzes::QuizStatistics::ItemAnalysis::Summary do
it "distributes the students accordingly" do it "distributes the students accordingly" do
buckets = summary.buckets buckets = summary.buckets
total = buckets.values.map(&:size).sum total = buckets.values.sum(&:size)
top, middle, bottom = buckets[:top].size / total.to_f, buckets[:middle].size / total.to_f, buckets[:bottom].size / total.to_f top, middle, bottom = buckets[:top].size / total.to_f, buckets[:middle].size / total.to_f, buckets[:bottom].size / total.to_f
# because of the small sample size, this is slightly off, but close enough for gvt work # because of the small sample size, this is slightly off, but close enough for gvt work

View File

@ -40,7 +40,7 @@ module Quizzes
def recipient_messages(target_group) def recipient_messages(target_group)
recipients = @finder.send("#{target_group}_students") recipients = @finder.send("#{target_group}_students")
recipients.map(&:all_conversations).map(&:size).reduce(:+) || 0 recipients.map(&:all_conversations).sum(&:size)
end end
end end
end end

View File

@ -108,7 +108,7 @@ describe 'Student Gradebook' do
means = [] means = []
[0, 3, 6].each do |i| [0, 3, 6].each do |i|
# the format below ensures that 18.0 is displayed as 18. # the format below ensures that 18.0 is displayed as 18.
mean = format('%g' % (('%.2f' % (grades[i, 3].inject { |a, e| a + e }.to_f / 3)))) mean = format('%g' % (('%.2f' % (grades[i, 3].sum.to_f / 3))))
means.push mean means.push mean
end end