-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add task solution #1547
base: master
Are you sure you want to change the base?
add task solution #1547
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,32 @@ | ||
'use strict'; | ||
|
||
// write your code here | ||
const elements = document.querySelectorAll('span.population'); | ||
const total = document.querySelector('span.total-population'); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Similarly, ensure that the 'total' and 'avgPop' elements are found before updating their innerText to prevent errors if they are missing. |
||
const avgPop = document.querySelector('span.average-population'); | ||
|
||
let sum = 0; | ||
let elementsCount = 0; | ||
|
||
for (const element of elements) { | ||
sum += +element.textContent.replace(/,/g, ''); | ||
elementsCount++; | ||
} | ||
|
||
const avg = sum / elementsCount; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ensure that 'elementsCount' is not zero before performing the division to avoid division by zero errors. Consider adding a check to handle cases where there are no elements. |
||
|
||
function formatNumber(value) { | ||
const strValue = value.toString(); | ||
let result = ''; | ||
|
||
for (let i = strValue.length; i > 0; i--) { | ||
if (i < strValue.length && (strValue.length - i) % 3 === 0) { | ||
result = ',' + result; | ||
} | ||
result = strValue[i - 1] + result; | ||
} | ||
|
||
return result; | ||
} | ||
|
||
total.innerText = formatNumber(sum); | ||
avgPop.innerText = formatNumber(avg.toFixed(0)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider checking if the elements are found before proceeding with calculations to avoid potential errors if the elements are not present in the DOM.