JavaScript: Data Aggregation (Numbers)
A separate class of problems that cannot do without loops is called data aggregation. Such problems include finding the maximum, the minimum, the sum, the arithmetic mean, and so on. Their main feature is that the result depends on the entire data set. To calculate the sum, you need to add up all the numbers; to find the maximum, you need to compare all the numbers.
Everyone who works with numbers is well familiar with such problems, for example, accountants or marketers. They are usually solved in spreadsheets like Microsoft Excel or Google Tables.
Let's look at the simplest example – finding the sum of a set of numbers. We will implement a function that adds up the numbers in a given range, including the boundaries. A range in this case is a series of numbers from some beginning to a certain end. For example, the range [1, 10] includes all integers from 1 to 10.
sumNumbersFromRange(5, 7); // 5 + 6 + 7 = 18
sumNumbersFromRange(1, 2); // 1 + 2 = 3
// [1, 1] a range with the same beginning and end is also a range
// it includes exactly one number – the boundary of the range itself
sumNumbersFromRange(1, 1); // 1
sumNumbersFromRange(100, 100); // 100To implement this code, we will need a loop, since adding numbers is an iterative process (it repeats for each number), and the number of iterations depends on the size of the range. Before looking at the code, try to answer the questions below:
- What value should the counter be initialized with?
- How will it change?
- When should the loop stop?
First try to think about these questions, and then look at the code below:
const sumNumbersFromRange = (start, finish) => {
// Technically you can change start
// But the input arguments should be left at their original value
// This makes the code easier to analyze
let i = start;
let sum = 0; // Initializing the sum
while (i <= finish) { // Moving to the end of the range
sum = sum + i; // Computing the sum for each number
i = i + 1; // Moving to the next number in the range
}
// Returning the resulting value
return sum;
};The general structure of the loop here is standard. There is a counter that is initialized with the starting value of the range, there is the loop itself with a stop condition when the end of the range is reached, and, finally, the change of the counter at the end of the loop body. The number of iterations in such a loop is equal to finish - start + 1. That is, for the range from 5 to 7 it is 7 - 5 + 1, which is 3 iterations.
The main differences from ordinary processing are related to the logic of computing the result. In aggregation problems, there is always some variable that stores the result of the loop's work inside itself. In the code above this is sum. On each iteration of the loop it changes, adding the next number in the range: sum = sum + i. The whole process looks like this:
// For the call sumNumbersFromRange(2, 5);
let sum = 0;
sum = sum + 2; // 2
sum = sum + 3; // 5
sum = sum + 4; // 9
sum = sum + 5; // 14
// 14 – the result of adding the numbers in the range [2, 5]The variable sum has an initial value equal to 0. Why set a value at all? Any repeating operation starts with some value. You cannot just declare a variable and start working with it inside a loop. This will lead to an incorrect result:
// the initial value is not set
// js automatically makes it equal to undefined
let sum;
// the first iteration of the loop
sum = sum + 2; // ?As a result of such a call, sum will contain NaN, that is, not a number. It arises from an attempt to add 2 and undefined. So some value is still needed. Why was 0 chosen in the code above? It is very easy to verify that all other options will lead to an incorrect result. If the initial value is equal to 1, then the result will be 1 more than needed.
In mathematics there is the concept of a neutral element of an operation (each operation has its own element). This concept has a very simple meaning. An operation with this element does not change the value on which the operation is performed. In addition, any number plus zero gives the number itself. With subtraction it is the same. Even concatenation has a neutral element – it is the empty string: '' + 'one' will be 'one'.
A self-check question. What is the neutral element of the multiplication operation? To answer this question, find the number that does not change any other numbers when multiplied by it.
Answer
The neutral element of multiplication is 1.
Instructions
Implement the function calculateElectricityBill(), which takes the number of kilowatt-hours consumed and returns the amount of the electricity bill.
A tiered tariff is in effect: the first 100 kWh cost 5 rubles each, the next 100 kWh cost 7 rubles each, and all kWh above 200 cost 10 rubles each.
Iterate over the consumption with a loop and gradually accumulate the total amount.
calculateElectricityBill(80); // => 400
calculateElectricityBill(150); // => 850
calculateElectricityBill(250); // => 1700Tips
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.
It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.
In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.
It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.
By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.
Создавать обучающие материалы, понятные для всех без исключения, довольно сложно. Мы очень стараемся, но всегда есть что улучшать. Если вы встретили материал, который вам непонятен, опишите проблему в обратной связи нашего сообщества
Your exercise will be checked with these tests:
import { expect, test } from 'vitest';
import f from './index.js';
test('test', () => {
expect(f(0)).toBe(0);
expect(f(80)).toBe(400);
expect(f(100)).toBe(500);
expect(f(150)).toBe(850);
expect(f(250)).toBe(1700);
});Teacher's solution will be available in:
20:00
