Skip to content
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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion src/scripts/main.js
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');

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.

const total = document.querySelector('span.total-population');

Choose a reason for hiding this comment

The 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;

Choose a reason for hiding this comment

The 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));
Loading