Skip to content

Commit b076397

Browse files
Merge pull request #196 from shchegol/master
Data types / Array methods
2 parents 7eb6e91 + 4f66f64 commit b076397

File tree

26 files changed

+422
-421
lines changed

26 files changed

+422
-421
lines changed
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
function camelize(str) {
22
return str
3-
.split('-') // splits 'my-long-word' into array ['my', 'long', 'word']
3+
.split('-') // разбивает 'my-long-word' на массив ['my', 'long', 'word']
44
.map(
5-
// capitalizes first letters of all array items except the first one
6-
// converts ['my', 'long', 'word'] into ['my', 'Long', 'Word']
5+
// Переводит в верхний регистр первые буквы всех элементом массива за исключением первого
6+
// превращает ['my', 'long', 'word'] в ['my', 'Long', 'Word']
77
(word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1)
88
)
9-
.join(''); // joins ['my', 'Long', 'Word'] into 'myLongWord'
9+
.join(''); // соединяет ['my', 'Long', 'Word'] в 'myLongWord'
1010
}
Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
1-
importance: 5
1+
важность: 5
22

33
---
44

5-
# Translate border-left-width to borderLeftWidth
5+
# Переведите текст вида border-left-width в borderLeftWidth
66

7-
Write the function `camelize(str)` that changes dash-separated words like "my-short-string" into camel-cased "myShortString".
7+
Напишите функцию `camelize(str)`, которая преобразует строки вида "my-short-string" в "myShortString".
88

9-
That is: removes all dashes, each word after dash becomes uppercased.
9+
То есть дефисы удаляются, а все слова после них получают заглавную букву.
1010

11-
Examples:
11+
Примеры:
1212

1313
```js
1414
camelize("background-color") == 'backgroundColor';
1515
camelize("list-style-image") == 'listStyleImage';
1616
camelize("-webkit-transition") == 'WebkitTransition';
1717
```
1818

19-
P.S. Hint: use `split` to split the string into an array, transform it and `join` back.
19+
P.S. Подсказка: используйте `split`, чтобы разбить строку на массив символов, потом переделайте всё как нужно и методом `join` соедините обратно.

1-js/05-data-types/05-array-methods/10-average-age/solution.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@ function getAverageAge(users) {
33
return users.reduce((prev, user) => prev + user.age, 0) / users.length;
44
}
55

6-
let john = { name: "John", age: 25 };
7-
let pete = { name: "Pete", age: 30 };
8-
let mary = { name: "Mary", age: 29 };
6+
let vasya = { name: "Вася", age: 25 };
7+
let petya = { name: "Петя", age: 30 };
8+
let masha = { name: "Маша", age: 29 };
99

10-
let arr = [ john, pete, mary ];
10+
let arr = [ vasya, petya, masha ];
1111

1212
alert( getAverageAge(arr) ); // 28
1313
```
Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
1-
importance: 4
1+
важность: 4
22

33
---
44

5-
# Get average age
5+
# Получить средний возраст
66

7-
Write the function `getAverageAge(users)` that gets an array of objects with property `age` and returns the average age.
7+
Напишите функцию `getAverageAge(users)`, которая принимает массив объектов со свойством `age` и возвращает средний возраст.
88

9-
The formula for the average is `(age1 + age2 + ... + ageN) / N`.
9+
Формула вычисления среднего арифметического значения: `(age1 + age2 + ... + ageN) / N`.
1010

11-
For instance:
11+
Например:
1212

1313
```js no-beautify
14-
let john = { name: "John", age: 25 };
15-
let pete = { name: "Pete", age: 30 };
16-
let mary = { name: "Mary", age: 29 };
14+
let vasya = { name: "Вася", age: 25 };
15+
let petya = { name: "Петя", age: 30 };
16+
let masha = { name: "Маша", age: 29 };
1717

18-
let arr = [ john, pete, mary ];
18+
let arr = [ vasya, petya, masha ];
1919

2020
alert( getAverageAge(arr) ); // (25 + 30 + 29) / 3 = 28
2121
```
Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
Let's walk the array items:
2-
- For each item we'll check if the resulting array already has that item.
3-
- If it is so, then ignore, otherwise add to results.
1+
Давайте пройдёмся по элементам массива:
2+
- Для каждого элемента мы проверим, есть ли он в массиве с результатом.
3+
- Если есть, то игнорируем его, а если нет - добавляем к результатам.
44

55
```js run demo
66
function unique(arr) {
@@ -15,25 +15,25 @@ function unique(arr) {
1515
return result;
1616
}
1717

18-
let strings = ["Hare", "Krishna", "Hare", "Krishna",
19-
"Krishna", "Krishna", "Hare", "Hare", ":-O"
18+
let strings = ["кришна", "кришна", "харе", "харе",
19+
"харе", "харе", "кришна", "кришна", ":-O"
2020
];
2121

22-
alert( unique(strings) ); // Hare, Krishna, :-O
22+
alert( unique(strings) ); // кришна, харе, :-O
2323
```
2424

25-
The code works, but there's a potential performance problem in it.
25+
Код работает, но в нём есть потенциальная проблема с производительностью.
2626

27-
The method `result.includes(str)` internally walks the array `result` and compares each element against `str` to find the match.
27+
Метод `result.includes(str)` внутри себя обходит массив `result` и сравнивает каждый элемент с `str`, чтобы найти совпадение.
2828

29-
So if there are `100` elements in `result` and no one matches `str`, then it will walk the whole `result` and do exactly `100` comparisons. And if `result` is large, like `10000`, then there would be `10000` comparisons.
29+
Таким образом, если `result` содержит `100` элементов и ни один не совпадает со `str`, тогда он обойдёт весь `result` и сделает ровно `100` сравнений. А если `result` большой, например, `10000`, то будет произведено `10000` сравнений.
3030

31-
That's not a problem by itself, because JavaScript engines are very fast, so walk `10000` array is a matter of microseconds.
31+
Само по себе это не проблема, потому что движки JavaScript очень быстрые, поэтому обход `10000` элементов массива занимает считанные микросекунды.
3232

33-
But we do such test for each element of `arr`, in the `for` loop.
33+
Но мы делаем такую проверку для каждого элемента `arr` в цикле `for`.
3434

35-
So if `arr.length` is `10000` we'll have something like `10000*10000` = 100 millions of comparisons. That's a lot.
35+
Поэтому, если `arr.length` равен `10000`, у нас будет что-то вроде `10000*10000` = 100 миллионов сравнений. Это многовато.
3636

37-
So the solution is only good for small arrays.
37+
Вот почему данное решение подходит только для небольших массивов.
3838

39-
Further in the chapter <info:map-set-weakmap-weakset> we'll see how to optimize it.
39+
Далее в главе <info:map-set-weakmap-weakset> мы увидим, как его оптимизировать.
Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
1-
importance: 4
1+
важность: 4
22

33
---
44

5-
# Filter unique array members
5+
# Оставить уникальные элементы массива
66

7-
Let `arr` be an array.
7+
Пусть `arr` – массив строк.
88

9-
Create a function `unique(arr)` that should return an array with unique items of `arr`.
9+
Напишите функцию unique(arr), которая возвращает массив, содержащий только уникальные элементы `arr`.
1010

11-
For instance:
11+
Например:
1212

1313
```js
1414
function unique(arr) {
15-
/* your code */
15+
/* ваш код */
1616
}
1717

18-
let strings = ["Hare", "Krishna", "Hare", "Krishna",
19-
"Krishna", "Krishna", "Hare", "Hare", ":-O"
18+
let strings = ["кришна", "кришна", "харе", "харе",
19+
"харе", "харе", "кришна", "кришна", ":-O"
2020
];
2121

22-
alert( unique(strings) ); // Hare, Krishna, :-O
22+
alert( unique(strings) ); // кришна, харе, :-O
2323
```
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

22
function filterRange(arr, a, b) {
3-
// added brackets around the expression for better readability
3+
// добавлены скобки вокруг выражения для лучшей читаемости
44
return arr.filter(item => (a <= item && item <= b));
55
}
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
```js run demo
22
function filterRange(arr, a, b) {
3-
// added brackets around the expression for better readability
3+
// добавлены скобки вокруг выражения для улучшения читабельности
44
return arr.filter(item => (a <= item && item <= b));
55
}
66

77
let arr = [5, 3, 8, 1];
88

99
let filtered = filterRange(arr, 1, 4);
1010

11-
alert( filtered ); // 3,1 (matching values)
11+
alert( filtered ); // 3,1 (совпадающие значения)
1212

13-
alert( arr ); // 5,3,8,1 (not modified)
13+
alert( arr ); // 5,3,8,1 (без изменений)
1414
```
Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
1-
importance: 4
1+
важность: 4
22

33
---
44

5-
# Filter range
5+
# Фильтрация по диапазону
66

7-
Write a function `filterRange(arr, a, b)` that gets an array `arr`, looks for elements between `a` and `b` in it and returns an array of them.
7+
Напишите функцию `filterRange(arr, a, b)`, которая принимает массив `arr`, ищет в нём элементы между `a` и `b` и отдаёт массив этих элементов.
88

9-
The function should not modify the array. It should return the new array.
9+
Функция должна возвращать новый массив и не изменять исходный.
1010

11-
For instance:
11+
Например:
1212

1313
```js
1414
let arr = [5, 3, 8, 1];
1515

1616
let filtered = filterRange(arr, 1, 4);
1717

18-
alert( filtered ); // 3,1 (matching values)
18+
alert( filtered ); // 3,1 (совпадающие значения)
1919

20-
alert( arr ); // 5,3,8,1 (not modified)
20+
alert( arr ); // 5,3,8,1 (без изменений)
2121
```
2222

1-js/05-data-types/05-array-methods/3-filter-range-in-place/_js.view/solution.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ function filterRangeInPlace(arr, a, b) {
44
for (let i = 0; i < arr.length; i++) {
55
let val = arr[i];
66

7-
// remove if outside of the interval
7+
// удалить, если за пределами интервала
88
if (val < a || val > b) {
99
arr.splice(i, 1);
1010
i--;

0 commit comments

Comments
 (0)