Skip to content

Commit fe8e1a2

Browse files
authored
Array methods (#192)
1 parent de6e13d commit fe8e1a2

File tree

26 files changed

+425
-425
lines changed

26 files changed

+425
-425
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
}

1-js/05-data-types/05-array-methods/1-camelcase/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,18 @@ importance: 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 ivan = { name: "Іван", age: 25 };
7+
let petro = { name: "Петро", age: 30 };
8+
let mariya = { name: "Марія", age: 29 };
99

10-
let arr = [ john, pete, mary ];
10+
let arr = [ ivan, petro, mariya ];
1111

1212
alert( getAverageAge(arr) ); // 28
1313
```

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ importance: 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
1414
let john = { name: "John", age: 25 };
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> we'll see how to optimize it.
39+
Далі в розділі <info:map-set> ми побачимо, як його оптимізувати.

1-js/05-data-types/05-array-methods/11-array-unique/task.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,22 @@ importance: 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
```

1-js/05-data-types/05-array-methods/12-reduce-object/task.md

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,36 +2,36 @@ importance: 4
22

33
---
44

5-
# Create keyed object from array
5+
# Створення об’єкта з ключем з масиву
66

7-
Let's say we received an array of users in the form `{id:..., name:..., age:... }`.
7+
Припустимо, ми отримали масив користувачів у вигляді `{id:..., name:..., age:...}`.
88

9-
Create a function `groupById(arr)` that creates an object from it, with `id` as the key, and array items as values.
9+
Створіть функцію `groupById(arr)`, яка створює з масиву об’єкт із ключом `id` та елементами масиву як значеннями.
1010

11-
For example:
11+
Наприклад:
1212

1313
```js
1414
let users = [
15-
{id: 'john', name: "John Smith", age: 20},
16-
{id: 'ann', name: "Ann Smith", age: 24},
17-
{id: 'pete', name: "Pete Peterson", age: 31},
15+
{id: 'іван', name: "Іван Іванко", age: 20},
16+
{id: 'ганна', name: "Ганна Іванко", age: 24},
17+
{id: 'петро', name: "Петро Петренко", age: 31},
1818
];
1919

2020
let usersById = groupById(users);
2121

2222
/*
23-
// after the call we should have:
23+
// після виклику функції ви повинні отримати:
2424
2525
usersById = {
26-
john: {id: 'john', name: "John Smith", age: 20},
27-
ann: {id: 'ann', name: "Ann Smith", age: 24},
28-
pete: {id: 'pete', name: "Pete Peterson", age: 31},
26+
іван: {id: 'іван', name: "Іван Іванко", age: 20},
27+
ганна: {id: 'ганна', name: "Ганна Іванко", age: 24},
28+
петро: {id: 'петро', name: "Петро Петренко", age: 31},
2929
}
3030
*/
3131
```
3232

33-
Such function is really handy when working with server data.
33+
Така функція дійсно зручна при роботі з даними сервера.
3434

35-
In this task we assume that `id` is unique. There may be no two array items with the same `id`.
35+
У цьому завданні ми вважаємо, що `id` унікальний. Не може бути двох елементів масиву з однаковими `id`.
3636

37-
Please use array `.reduce` method in the solution.
37+
Будь ласка, використовуйте метод масиву `.reduce` у рішенні.
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
```

1-js/05-data-types/05-array-methods/2-filter-range/task.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,21 @@ importance: 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 with values higher or equal to `a` and lower or equal to `b` and return a result as an array.
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

0 commit comments

Comments
 (0)