JavaScript: Data aggregation (Strings)
Aggregation applies not only to numbers but also to strings. These are tasks in which a string is built dynamically, that is, it is not known in advance how big it will be or what it will contain.
Imagine a function that can "multiply" a string, that is, it repeats it a specified number of times:
repeat('hexlet', 3); // hexlethexlethexletThe way this function works is quite simple: in a loop, the string is "grown" the specified number of times:
const repeat = (text, times) => {
// The neutral element for strings is the empty string
let result = '';
let i = 1;
while (i <= times) {
// Each time we add the string to the result
result = `${result}${text}`;
i = i + 1;
}
return result;
};Let's break down the execution of this code step by step:
// For the call repeat('hexlet', 3);
let result = '';
result = `${result}hexlet`; // hexlet
result = `${result}hexlet`; // hexlethexlet
result = `${result}hexlet`; // hexlethexlethexletVisually, the process of growing the string looks like this:
repeat('hexlet', 3):
i=1: result = '' + 'hexlet' = 'hexlet'
i=2: result = 'hexlet' + 'hexlet' = 'hexlethexlet'
i=3: result = 'hexlethexlet' + 'hexlet' = 'hexlethexlethexlet'
└── resultNeutral element
For growing to work, a starting value is needed. For strings, this value is the empty string ''.
It is called the neutral element because it changes nothing during concatenation:
console.log('' + 'abc'); // => abc
console.log('abc' + ''); // => abcThat is why the empty string is always used as the initial value when aggregating strings.
Instructions
Implement a function sanitizePhoneNumber() that takes a phone number from a form and returns a string without spaces, parentheses, and hyphens.
Users enter numbers in different ways, but before saving them they are normalized to a single format. Go through the original string character by character and assemble a new number using only the useful characters.
sanitizePhoneNumber('+7 (999) 123-45-67'); // => '+79991234567'
sanitizePhoneNumber('8 800 555 35 35'); // => '88005553535'
sanitizePhoneNumber('(123) 456-7890'); // => '1234567890'Use the empty string as the initial value.
Tips
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('+7 (999) 123-45-67')).toBe('+79991234567');
expect(f('8 800 555 35 35')).toBe('88005553535');
expect(f('(123) 456-7890')).toBe('1234567890');
});Teacher's solution will be available in:
20:00
