chore(i18n,curriculum): processed translations - new ukrainian (#44447)

This commit is contained in:
camperbot
2021-12-10 11:14:24 +05:30
committed by GitHub
parent 8651ee1797
commit 0473dedf47
1663 changed files with 156692 additions and 1 deletions

View File

@@ -0,0 +1,88 @@
---
id: 587d7da9367417b2b2512b67
title: Додати елементи в кінець масиву за допомогою контикату замість натискання
challengeType: 1
forumTopicId: 301226
dashedName: add-elements-to-the-end-of-an-array-using-concat-instead-of-push
---
# --description--
Функціональне програмування - це створення та використання функцій, що не змінюються.
Останній виклик представив метод `контикату ` як спосіб об'єднання масивів у новий без мутації вихідних масивів. Порівняйте метод `concat` з методом `push`. `push` додає елемент в кінець викликаного масиву, який змінює його. Ось один із прикладів:
```js
const arr = [1, 2, 3];
arr.push([4, 5, 6]);
```
`arr` матиме модифіковане значення `[1, 2, 3, [4, 5, 6]]`,що не є функціональним способом програмування.
`concat` пропонує спосіб додавання нових елементів до кінця масиву без побічних ефектів, що мутують.
# --instructions--
Змініть функцію `nonMutatingPush` так що вона використовує `concat`, щоб додати `newItem` до кінця `original` замість `push`. Функція повинна повертати масив.
# --hints--
Ваш код повинен застосовувати метод `concat`.
```js
assert(code.match(/\.concat/g));
```
Не застосовуйте метод `push` у вашому коді.
```js
assert(!code.match(/\.?[\s\S]*?push/g));
```
Масив `first` не повинен змінюватись.
```js
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
```
Масив `second` не повинен змінюватись.
```js
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
```
`nonMutatingConcat([1, 2, 3], [4, 5])` повинен змінюватися на `[1, 2, 3, 4, 5]`.
```js
assert(
JSON.stringify(nonMutatingPush([1, 2, 3], [4, 5])) ===
JSON.stringify([1, 2, 3, 4, 5])
);
```
# --seed--
## --seed-contents--
```js
function nonMutatingPush(original, newItem) {
// Only change code below this line
return original.push(newItem);
// Only change code above this line
}
const first = [1, 2, 3];
const second = [4, 5];
nonMutatingPush(first, second);
```
# --solutions--
```js
function nonMutatingPush(original, newItem) {
return original.concat(newItem);
}
const first = [1, 2, 3];
const second = [4, 5];
```

View File

@@ -0,0 +1,83 @@
---
id: 587d7dab367417b2b2512b6d
title: Застосуйте функціональне програмування для перетворення рядків в URL потоки
challengeType: 1
forumTopicId: 301227
dashedName: apply-functional-programming-to-convert-strings-to-url-slugs
---
# --description--
Останні кілька викликів охопили ряд корисних масивів та рядкових методів, що дотримуються принципів функціонального програмування. Ми також дізналися про `reduce`, який є потужним методом, що використовується для зменшення проблем для більш простої форми. Від середнього рівня обчислення до сортування, будь-яку масивну операцію можна досягти шляхом її застосування. Згадайте, що `map` і `filter` є особливими випадками `reduce`.
Об'єднаймо те, що ми навчилися вирішувати практичні проблеми.
Багато сайтів управління контентом (CMS) мають заголовки матеріалу, доданих до частини URL для простих закладок. Наприклад, якщо ви напишете середній пост під назвою `Stop Using Reduce`, ймовірно, що URL буде мати певний формат рядка з заголовком (`.../stop-using-reduce`). Можливо, ви вже помітили це на сайті freeCodeCamp.
# --instructions--
Заповніть функцію `urlSlug`, щоб вона конвертувала рядок `title` і повертала версію з дефісом для URL. Ви можете використати будь-який з методів, використаних у цьому розділі, і не використовуйте `replace`. Ось вимоги:
Вхідний - це рядок з пробілами і текстовими словами
Вихідний рядок з пробілами між словами, заміненим на дефіс (`-`)
Вихідний рядок повинен бути весь малими літерами
Вихідний рядок не повинен мати жодних пробілів
# --hints--
Не використовуйте метод `replace` у вашому коді для цього завдання.
```js
assert(!code.match(/\.?[\s\S]*?replace/g));
```
`urlSlug("Winter Is Coming")` повинен повернути рядок `winter-is-coming`.
```js
assert(urlSlug('Winter Is Coming') === 'winter-is-coming');
```
`urlSlug("Winter Is Coming")` повернути рядок `winter-is-coming`.
```js
assert(urlSlug(' Winter Is Coming') === 'winter-is-coming');
```
`urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")` потрібно повернути рядок `a-mind-needs-books-like-a-sword-needs-needs-a-whetstone`.
```js
assert(
urlSlug('A Mind Needs Books Like A Sword Needs A Whetstone') ===
'a-mind-needs-books-like-a-sword-needs-a-whetstone'
);
```
`urlSlug(" Hold The Door")`слід повернути рядок `hold-door`.
```js
assert(urlSlug('Hold The Door') === 'hold-the-door');
```
# --seed--
## --seed-contents--
```js
// Only change code below this line
function urlSlug(title) {
}
// Only change code above this line
```
# --solutions--
```js
function urlSlug(title) {
return title.trim().split(/\s+/).join("-").toLowerCase();
}
```

View File

@@ -0,0 +1,78 @@
---
id: 587d7b8e367417b2b2512b5e
title: Уникайте будь-яких змін та побічних ефектів, використовуючи функціональне програмування
challengeType: 1
forumTopicId: 301228
dashedName: avoid-mutations-and-side-effects-using-functional-programming
---
# --description--
Якщо ви ще цього не зрозуміли, проблема в попередньому завданні була з `splice` у функції `Close()`. На жаль, `splice` змінює вихідний масив, в якому він викликається, тому другий дзвінок використовував модифікований масив і дав несподівані результати.
Це невеликий приклад набагато більшого шаблону - викликається функція змінної, масиву або об'єкта, а функція змінює саме змінну чи щось інше в об’єкті.
Одним з основних принципів функціонального програмування - не змінювати речі. Зміни призводять до помилок. Легше уникнути помилок, знаючи, що ваші функції нічого не змінюють, включаючи аргументи функцій чи будь-яку іншу глобальну змінну.
Попередній приклад не мав жодних складних операцій, але метод `splice` змінив оригінальний масив і видав помилку.
Нагадаємо, що у функціональному програмуванні зміни або зміна речей називається <dfn>мутацією</dfn>, і наслідок називається <dfn>побічним ефектом</dfn>. В ідеалі функція, повинна бути <dfn>pure function</dfn>, це означає, що вона не спричиняє жодних побічних ефектів.
Давайте спробуємо освоїти цю дисципліну і не будемо змінювати будь-які змінні або об'єкти в нашому коді.
# --instructions--
Ввести код для функції`incrementer` таким чином, значення глобальної змінної `fixedValue` зросло в один раз.
# --hints--
Ваша функція `incrementer` не повинна змінювати значення `fixedValue` (яка є `4`).
```js
incrementer();
assert(fixedValue === 4);
```
Ваша функція `incrementer` повертає значення, яке на одиницю більше значення `fixedValue`.
```js
const __newValue = incrementer();
assert(__newValue === 5);
```
Ваша функція `incrementer` повинна повертати значення на основі глобального змінного значення `fixedValue`.
```js
(function () {
fixedValue = 10;
const newValue = incrementer();
assert(fixedValue === 10 && newValue === 11);
fixedValue = 4;
})();
```
# --seed--
## --seed-contents--
```js
// The global variable
let fixedValue = 4;
function incrementer() {
// Only change code below this line
// Only change code above this line
}
```
# --solutions--
```js
let fixedValue = 4
function incrementer() {
return fixedValue + 1
}
```

View File

@@ -0,0 +1,89 @@
---
id: 587d7daa367417b2b2512b6c
title: Об'єднання масиву у рядок з використанням методу Join
challengeType: 1
forumTopicId: 18221
dashedName: combine-an-array-into-a-string-using-the-join-method
---
# --description--
Метод `join` використовується для об'єднання елементів масиву для створення стрічки. Потрібний аргумент для розділювача, який використовується для відокремлення елементів масиву у рядку.
Наприклад:
```js
const arr = ["Hello", "World"];
const str = arr.join(" ");
```
`str` матиме значення рядка `Hello World`.
# --instructions--
Використовуйте метод `join` (з-поміж інших) у функції `sentensify` для створення речення зі слів у рядку `str`. Ваша функція повинна повертати рядок. Наприклад, `I-like-Star-Wars` буде перетворений в `I like Star Wars`. Для цього завдання не використовуйте метод `replace`.
# --hints--
Використовуйте метод `join` у вашому коді.
```js
assert(code.match(/\.join/g));
```
Не використовуйте метод `replace` у вашому коді.
```js
assert(!code.match(/\.?[\s\S]*?replace/g));
```
`sentensify("May-the-force-be-with-you")` повинен повертати рядок.
```js
assert(typeof sentensify('May-the-force-be-with-you') === 'string');
```
`sentensify("May-the-force-be-with-you")` повинен повертати рядок `May the force be with you`.
```js
assert(sentensify('May-the-force-be-with-you') === 'May the force be with you');
```
`sentensify("The.force.is.strong.with.this.one")` повинен повертати рядок `The force is strong with this one`.
```js
assert(
sentensify('The.force.is.strong.with.this.one') ===
'The force is strong with this one'
);
```
`sentensify("There,has,been,an,awakening")` повинен повертати рядок `There has been an awakening`.
```js
assert(
sentensify('There,has,been,an,awakening') === 'There has been an awakening'
);
```
# --seed--
## --seed-contents--
```js
function sentensify(str) {
// Only change code below this line
// Only change code above this line
}
sentensify("May-the-force-be-with-you");
```
# --solutions--
```js
function sentensify(str) {
return str.split(/\W/).join(' ');
}
```

View File

@@ -0,0 +1,77 @@
---
id: 587d7da9367417b2b2512b66
title: Об'єднуйте два масиви за допомогою методу concat
challengeType: 1
forumTopicId: 301229
dashedName: combine-two-arrays-using-the-concat-method
---
# --description--
<dfn>Concatenation</dfn> означає з'єднання елементів від одного кінця до іншого. JavaScript пропонує метод `concat` як для змінних рядкового типу, так і для масивів, що працюють таким же чином. Для масивів, метод викликається на один, потім інший масив надається як аргумент `concat`, який додається до кінця першого масиву. Він повертає новий масив та не змінює жодного з оригінальних масивів. Ось приклад:
```js
[1, 2, 3].concat([4, 5, 6]);
```
Масив, що повертається, буде `[1, 2, 3, 4, 5, 6]`.
# --instructions--
Використовуйте метод `concat` в функції `nonMutatingConcat` для конкатенації `attach` до кінця `original`. Функція повинна повернути конкатенований масив.
# --hints--
Ваш код повинен використовувати метод `concat`.
```js
assert(code.match(/\.concat/g));
```
Масив `first` не повинен змінюватись.
```js
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
```
Масив `second` не повинен змінюватись.
```js
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
```
`nonMutatingConcat([1, 2, 3], [4, 5])` повинен повертати `[1, 2, 3, 4, 5]`.
```js
assert(
JSON.stringify(nonMutatingConcat([1, 2, 3], [4, 5])) ===
JSON.stringify([1, 2, 3, 4, 5])
);
```
# --seed--
## --seed-contents--
```js
function nonMutatingConcat(original, attach) {
// Only change code below this line
// Only change code above this line
}
const first = [1, 2, 3];
const second = [4, 5];
nonMutatingConcat(first, second);
```
# --solutions--
```js
function nonMutatingConcat(original, attach) {
return original.concat(attach);
}
const first = [1, 2, 3];
const second = [4, 5];
```

View File

@@ -0,0 +1,72 @@
---
id: 587d7b8f367417b2b2512b62
title: Карта реалізації на прототипі
challengeType: 1
forumTopicId: 301230
dashedName: implement-map-on-a-prototype
---
# --description--
Як ви бачили з використання `Array.prototype.map()`, або просто `map()` раніше, метод `map` повертає масив тієї ж довжини, що і той, на який був викликаний. Він також не змінює оригінальний масив, поки його функція зворотного виклику не змінюється.
Іншими словами, `map` - це чиста функція, і її вихід залежить виключно від вхідних даних. Крім того, в якості аргумента використовується інша функція.
Ви можете багато дізнатись про метод `map`, якщо ви реалізуєте вашу власну версію. Рекомендується використовувати код циклу `for` або `Array.prototype.forEach()`.
# --instructions--
Напишіть ваш власний `Array.prototype.myMap()`, що повинен поводити себе точно так як `Array.prototype.map()`. Не варто використовувати вбудований метод `map`. Екземпляр `Array` може бути доступним за допомогою методу `myMap` з використанням `this`.
# --hints--
`new_s` повинне дорівнювати `[46, 130, 196, 10]`.
```js
assert(JSON.stringify(new_s) === JSON.stringify([46, 130, 196, 10]));
```
Не використовуйте метод `map` у вашому коді.
```js
assert(!code.match(/\.?[\s\S]*?map/g));
```
# --seed--
## --seed-contents--
```js
// The global variable
const s = [23, 65, 98, 5];
Array.prototype.myMap = function(callback) {
const newArray = [];
// Only change code below this line
// Only change code above this line
return newArray;
};
const new_s = s.myMap(function(item) {
return item * 2;
});
```
# --solutions--
```js
const s = [23, 65, 98, 5];
Array.prototype.myMap = function(callback) {
const newArray = [];
for (const elem of this) {
newArray.push(callback(elem));
}
return newArray;
};
const new_s = s.myMap(function(item) {
return item * 2;
});
```

View File

@@ -0,0 +1,67 @@
---
id: 587d7b8f367417b2b2512b64
title: Реалізація методу фільтра для прототипу
challengeType: 1
forumTopicId: 301231
dashedName: implement-the-filter-method-on-a-prototype
---
# --description--
Ви можете багато дізнатись про метод `filter`, якщо ви реалізуєте вашу власну версію. Рекомендується використовувати код циклу `for` або `Array.prototype.forEach()`.
# --instructions--
Напишіть ваш власний `Array.prototype.myFilter()`, який буде поводити себе точно так як `Array.prototype.filter()`. Не варто використовувати вбудований метод `filter`. Приклад `Array` може бути доступним за допомогою методу `myFilter` з використанням `this`.
# --hints--
`new_s` повинне дорівнювати `[23, 65, 5]`.
```js
assert(JSON.stringify(new_s) === JSON.stringify([23, 65, 5]));
```
Не використовуйте метод `filter` для вашого коду.
```js
assert(!code.match(/\.?[\s\S]*?filter/g));
```
# --seed--
## --seed-contents--
```js
// The global variable
const s = [23, 65, 98, 5];
Array.prototype.myFilter = function(callback) {
// Only change code below this line
const newArray = [];
// Only change code above this line
return newArray;
};
const new_s = s.myFilter(function(item) {
return item % 2 === 1;
});
```
# --solutions--
```js
const s = [23, 65, 98, 5];
Array.prototype.myFilter = function(callback) {
const newArray = [];
for (let i = 0; i < this.length; i++) {
if (callback(this[i])) newArray.push(this[i]);
}
return newArray;
};
const new_s = s.myFilter(function(item) {
return item % 2 === 1;
});
```

View File

@@ -0,0 +1,102 @@
---
id: 587d7dab367417b2b2512b70
title: Вступ до каррування та часткового застосування функції
challengeType: 1
forumTopicId: 301232
dashedName: introduction-to-currying-and-partial-application
---
# --description--
<dfn>Арність</dfn> функції це кількість необхідних їй аргументів. <dfn>Каррування</dfn> функції означає перетворення функції з арністю N на функції N з арністю 1.
Інакше кажучи, каррування реструктурує функцію так, що вона бере один аргумент, потім повертає іншу функцію, яка бере наступний аргумент, і так далі.
Наприклад:
```js
function unCurried(x, y) {
return x + y;
}
function curried(x) {
return function(y) {
return x + y;
}
}
const curried = x => y => x + y
curried(1)(2)
```
`curried(1)(2)` перетвориться на `3`.
Це знадобиться у вашій програмі, якщо ви не можете надати всі аргументи до функції одночасно. Ви можете зберегти кожен виклик функції в змінну, яка матиме посилання на повернуту функцію, що візьме наступний аргумент, коли він буде доступним. Ось приклад використання згаданої вище функції каррування:
```js
const funcForY = curried(1);
console.log(funcForY(2)); // 3
```
Аналогічно <dfn>часткове застосування</dfn> можна описати як застосування декількох аргументів до функції одночасно і повернення іншої функції, яка застосовується до більшої кількості аргументів. Наприклад:
```js
function impartial(x, y, z) {
return x + y + z;
}
const partialFn = impartial.bind(this, 1, 2);
partialFn(10); // 13
```
# --instructions--
Заповніть тіло функції `add` так, щоб використовувалось каррування для додавання параметрів `x`, `y` та `z`.
# --hints--
`add(10)(20)(30)` потрібно повернути `60`.
```js
assert(add(10)(20)(30) === 60);
```
`add(1)(2)(3)` потрібно повернути `6`.
```js
assert(add(1)(2)(3) === 6);
```
`add(11)(22)(33)` потрібно повернути `66`.
```js
assert(add(11)(22)(33) === 66);
```
Ваш код має містити остаточне твердження, яке повертає до `x + y + z`.
```js
assert(code.match(/[xyz]\s*?\+\s*?[xyz]\s*?\+\s*?[xyz]/g));
```
# --seed--
## --seed-contents--
```js
function add(x) {
// Only change code below this line
// Only change code above this line
}
add(10)(20)(30);
```
# --solutions--
```js
const add = x => y => z => x + y + z
```

View File

@@ -0,0 +1,86 @@
---
id: 587d7b8d367417b2b2512b5b
title: Дізнайтеся про функціональне програмування
challengeType: 1
forumTopicId: 301233
dashedName: learn-about-functional-programming
---
# --description--
Функціональне програмування - це стиль програмування, в якому рішення - це прості, ізольовані функції, без будь-яких побічних ефектів, що виходять за межі області дії функції: `INPUT -> PROCESS -> OUTPUT`
Функціональне програмування передбачає:
1) Ізольовані функції: без будь-якої залежності від стану програми, що містить глобальні змінні, які можуть бути змінені
2) Чиста функція: один і той же вхід завжди дає однаковий вихід
3) Функції з обмеженими побічними ефектами: будь-які зміни чи мутації стану програми за межами функції ретельно контролюються
# --instructions--
Учасники FreeCodeCamp полюблять чай.
У редакторі коді `prepareTea` і `getTea` для вас вже визначено функції. Викличте функцію `getTea`, щоб отримати 40 чашок чаю для команди, і збережіть їх у змінній `tea4TeamFCC`.
# --hints--
Змінна `tea4TeamFCC` повинна містити 40 чашок чаю для команди.
```js
assert(tea4TeamFCC.length === 40);
```
Змінна `tea4TeamFCC` повинна містити чашки зеленого чаю.
```js
assert(tea4TeamFCC[0] === 'greenTea');
```
# --seed--
## --seed-contents--
```js
// Function that returns a string representing a cup of green tea
const prepareTea = () => 'greenTea';
/*
Given a function (representing the tea type) and number of cups needed, the
following function returns an array of strings (each representing a cup of
a specific type of tea).
*/
const getTea = (numOfCups) => {
const teaCups = [];
for(let cups = 1; cups <= numOfCups; cups += 1) {
const teaCup = prepareTea();
teaCups.push(teaCup);
}
return teaCups;
};
// Only change code below this line
const tea4TeamFCC = null;
// Only change code above this line
```
# --solutions--
```js
const prepareTea = () => 'greenTea';
const getTea = (numOfCups) => {
const teaCups = [];
for(let cups = 1; cups <= numOfCups; cups += 1) {
const teaCup = prepareTea();
teaCups.push(teaCup);
}
return teaCups;
};
const tea4TeamFCC = getTea(40);
```

View File

@@ -0,0 +1,74 @@
---
id: 587d7b8e367417b2b2512b5f
title: Передавайте аргументи, щоб уникнути зовнішньої залежності у функції
challengeType: 1
forumTopicId: 301234
dashedName: pass-arguments-to-avoid-external-dependence-in-a-function
---
# --description--
Остання задача полягала в тому, щоб на крок приблизитись до функціональних принципів програмування, однак все ще чогось не вистачає.
Ми не змінили значення глобальної змінної, але функція `incrementer` не буде працювати без глобальної змінної `fixedValue` being there.
Інший принцип функціонального програмування - завжди відкрито заявляти про свої залежності. Це означає, що якщо функція залежить від змінної чи об'єкту, тоді ця змінна чи об'єкт передаються безпосередньо в функцію в якості аргументу.
Цей принцип має ряд хороших наслідків. Цю функцію легше перевірити, ви точно знаєте, який вхід потребується, і вона ні від чого не буде залежати у вашій програмі.
Це може дати вам більше впевненості при зміні чи видаленні, чи додаванні нового коду. Ви б знали, що ви можете чи не можете змінити, і ви можете бачити, де розміщені потенційні пастки.
Нарешті, функція завжди виробляє один і той же набір вхідних данних, незалежно від того, яка частина коду його виконує.
# --instructions--
Давайте оновимо функцію `incrementer` для чіткого визначення залежностей.
Напишіть функцію `incrementer` так, щоб вона прийняла аргумент, а потім повертала результат після збільшення значення на одиницю.
# --hints--
Ваша функція `incrementer` не повинна змінювати значення `fixedValue` (яка є `4`).
```js
assert(fixedValue === 4);
```
Ваша функція `incrementer` повинна прийняти аргумент.
```js
assert(incrementer.length === 1);
```
Ваша функція `incrementer` повинна повернути значення, що на одиницю більше значення `fixedValue` value.
```js
const __newValue = incrementer(fixedValue);
assert(__newValue === 5);
```
# --seed--
## --seed-contents--
```js
// The global variable
let fixedValue = 4;
// Only change code below this line
function incrementer() {
// Only change code above this line
}
```
# --solutions--
```js
let fixedValue = 4;
function incrementer(fixedValue) {
return fixedValue + 1;
}
```

View File

@@ -0,0 +1,141 @@
---
id: 587d7b8f367417b2b2512b60
title: Зміна глобальних змінних поза функціями
challengeType: 1
forumTopicId: 301235
dashedName: refactor-global-variables-out-of-functions
---
# --description--
На сьогодні ми спостерігаємо два окремих принципи функціонального програмування:
1) Не змінюйте змінну чи об'єкт - створюйте нові змінні і об'єкти та повертайте їх через функцію, якщо це необхідно. Підказка: використання чогось на зразок `const newArr = arrVar` (де `arrVar` є масивом) просто створить посилання на оригінальну змінну, а не копію. Таким чином, зміна значення в `newArr` змінить значення в `arrVar`.
2) Оголошення параметрів функції - будь-яке обчислення всередині функції залежить лише від аргументів, переданих функції, а не від будь-якого глобального об'єкту чи змінної.
Додавання такого числа не є дуже захопливим, але ми можемо застосувати ці принципи при роботі з масивами або більш складними об'єктами.
# --instructions--
Перепишіть код так, щоб глобальний масив `bookList` не змінювався всередині кожної функції. Функція `add` повинна додати цей код `bookName` в кінець масиву та повернути новий масив ( список). Функція `remove` повинна видалити вказану `bookName` з масиву, переданого до неї.
**Note:** Обидві функції повинні повертати масив, і будь-які нові параметри повинні бути додані перед параметром `bookName`.
# --hints--
`bookList` не повинен змінюватися і, як і раніше, дорівнювати `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`.
```js
assert(
JSON.stringify(bookList) ===
JSON.stringify([
'The Hound of the Baskervilles',
'On The Electrodynamics of Moving Bodies',
'Philosophiæ Naturalis Principia Mathematica',
'Disquisitiones Arithmeticae'
])
);
```
`newBookList` повинен дорівнювати `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`.
```js
assert(
JSON.stringify(newBookList) ===
JSON.stringify([
'The Hound of the Baskervilles',
'On The Electrodynamics of Moving Bodies',
'Philosophiæ Naturalis Principia Mathematica',
'Disquisitiones Arithmeticae',
'A Brief History of Time'
])
);
```
`newerBookList` повинен дорівнювати `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`.
```js
assert(
JSON.stringify(newerBookList) ===
JSON.stringify([
'The Hound of the Baskervilles',
'Philosophiæ Naturalis Principia Mathematica',
'Disquisitiones Arithmeticae'
])
);
```
`newestBookList` повинен дорівнювати `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`.
```js
assert(
JSON.stringify(newestBookList) ===
JSON.stringify([
'The Hound of the Baskervilles',
'Philosophiæ Naturalis Principia Mathematica',
'Disquisitiones Arithmeticae',
'A Brief History of Time'
])
);
```
# --seed--
## --seed-contents--
```js
// The global variable
const bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
// Change code below this line
function add (bookName) {
bookList.push(bookName);
return bookList;
// Change code above this line
}
// Change code below this line
function remove (bookName) {
const book_index = bookList.indexOf(bookName);
if (book_index >= 0) {
bookList.splice(book_index, 1);
return bookList;
// Change code above this line
}
}
const newBookList = add(bookList, 'A Brief History of Time');
const newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
const newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
console.log(bookList);
```
# --solutions--
```js
// The global variable
const bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
function add(bookList, bookName) {
return [...bookList, bookName];
}
function remove(bookList, bookName) {
const bookListCopy = [...bookList];
const bookNameIndex = bookList.indexOf(bookName);
if (bookNameIndex >= 0) {
bookListCopy.splice(bookNameIndex, 1);
}
return bookListCopy;
}
const newBookList = add(bookList, 'A Brief History of Time');
const newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
const newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
```

View File

@@ -0,0 +1,84 @@
---
id: 9d7123c8c441eeafaeb5bdef
title: Видалення елементів з масиву з використанням slice замість splice
challengeType: 1
forumTopicId: 301236
dashedName: remove-elements-from-an-array-using-slice-instead-of-splice
---
# --description--
Загальним шаблоном під час роботи з масивами є те, коли ви хочете видалити елементи й зберегти решту масиву. JavaScript пропонує для цього метод « `splice`», який приймає аргументи для індексу, де саме починати видаляти елементи, а тоді — їх кількість. Якщо другий аргумент не було надано, то, за замовчуванням, елементи видаляються до кінця. Щоправда, метод «`splice`» змінює оригінальний масив, у якому викликається. Ось приклад:
```js
const cities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
cities.splice(3, 1);
```
Тут `splice` повертає рядок `London` і видаляє його із масиву міст. `cities` матимуть значення `["Chicago", "Delhi", "Islamabad", "Berlin"]`.
Як ми могли бачити у останньому завдання, метод «`slice`» не змінює вихідного масиву, але повертає новий, який може бути збережений як змінний. Пригадайте, що метод «`slice`» використовує два аргументи для того, щоб індекси почали та закінчили slice (кінець не включається); і повертає ці елементи у новий масив. Використання методу «`slice`» замість «`splice`» допомагає уникнути будь-яких побічних дій зміни масиву.
# --instructions--
Перепишіть функцію `nonMutatingSplice`, використовуючи `slice` замість `splice`. Він мусить обмежити наданий масив `cities` до довжини 3, і повернути новий масив лише із першими трьома елементами.
Не змінюйте вихідний масив, наданий функцією.
# --hints--
Використовуйте метод «`slice`» у своєму коді.
```js
assert(code.match(/\.slice/g));
```
Не використовуйте метод «`splice`» у своєму коді.
```js
assert(!code.match(/\.?[\s\S]*?splice/g));
```
Масив `inputCities` не повинен змінюватись.
```js
assert(
JSON.stringify(inputCities) ===
JSON.stringify(['Chicago', 'Delhi', 'Islamabad', 'London', 'Berlin'])
);
```
`nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])` повинен повертатися як `["Chicago", "Delhi", "Islamabad"]`.
```js
assert(
JSON.stringify(
nonMutatingSplice(['Chicago', 'Delhi', 'Islamabad', 'London', 'Berlin'])
) === JSON.stringify(['Chicago', 'Delhi', 'Islamabad'])
);
```
# --seed--
## --seed-contents--
```js
function nonMutatingSplice(cities) {
// Only change code below this line
return cities.splice(3);
// Only change code above this line
}
const inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
nonMutatingSplice(inputCities);
```
# --solutions--
```js
function nonMutatingSplice(cities) {
return cities.slice(0,3);
}
const inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
```

View File

@@ -0,0 +1,90 @@
---
id: 587d7da9367417b2b2512b6a
title: Повернення відсортованого масиву без зміни вихідного масиву
challengeType: 1
forumTopicId: 301237
dashedName: return-a-sorted-array-without-changing-the-original-array
---
# --description--
Побічним ефектом методу «`sort`» є те, що він змінює порядок елементів у вихідному масиві. Іншими словами, він змінює масив. Одним із способів уникнення цього є, по-перше, об'єднати пустий масив із тим, що вже є відсортованим (пам'ятайте, що `slice` та `concat` повертають новий масив), а тоді запустити метод «`sort`».
# --instructions--
Використовуйте метод `sort` у функції `nonMutatingSort`, щоб відсортувати елементи масиву у висхідному порядку. Функція повинна повернути новий масив і не змінювати змінну `globalArray`.
# --hints--
Використовуйте метод «`sort`» у вашому коді.
```js
assert(nonMutatingSort.toString().match(/\.sort/g));
```
Змінна `globalArray` не повинна змінитися.
```js
assert(JSON.stringify(globalArray) === JSON.stringify([5, 6, 3, 2, 9]));
```
`nonMutatingSort(globalArray)` повинен повертати `[2, 3, 5, 6, 9]`.
```js
assert(
JSON.stringify(nonMutatingSort(globalArray)) ===
JSON.stringify([2, 3, 5, 6, 9])
);
```
`nonMutatingSort(globalArray)` не мусить бути складно закодованим.
```js
assert(!nonMutatingSort.toString().match(/\[.*?[23569].*?\]/gs));
```
Функція повинна повертатися як новий масив, а не масив передаватись через неї.
```js
assert(nonMutatingSort(globalArray) !== globalArray);
```
`nonMutatingSort([1, 30, 4, 21, 100000])` повинен повертатися як `[1, 4, 21, 30, 100000]`.
```js
assert(JSON.stringify(nonMutatingSort([1, 30, 4, 21, 100000])) ===
JSON.stringify([1, 4, 21, 30, 100000]))
```
`nonMutatingSort([140000, 104, 99])` повинен повертатися як `[99, 104, 140000]`.
```js
assert(JSON.stringify(nonMutatingSort([140000, 104, 99])) ===
JSON.stringify([99, 104, 140000]))
```
# --seed--
## --seed-contents--
```js
const globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
// Only change code below this line
// Only change code above this line
}
nonMutatingSort(globalArray);
```
# --solutions--
```js
const globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
return [].concat(arr).sort((a,b) => a-b);
}
```

View File

@@ -0,0 +1,93 @@
---
id: 587d7b90367417b2b2512b65
title: Повернення частини масиву з використанням методу slice
challengeType: 1
forumTopicId: 301239
dashedName: return-part-of-an-array-using-the-slice-method
---
# --description--
Метод «`slice`» повертає копію певних елементів масиву. Він використовує два аргументи: перший бере індекс, де починається slice, і другий — це індекс, де slice закінчується (не включно). Якщо аргументи не надані, то за замовчуванням - почати з початку масиву і дійти до кінця, що є не найлегшим способом скопіювати весь масив. Метод «`slice`» не змінює вихідний масив, але повертає новий.
Ось приклад:
```js
const arr = ["Cat", "Dog", "Tiger", "Zebra"];
const newArray = arr.slice(1, 3);
```
`newArray` матиме значення `["Dog", "Tiger"]`.
# --instructions--
Використовуйте метод «`slice`» у функції `sliceArray` для того, щоб повернути частину масиву `anim`, що обумовлений наданими індексами `beginSlice` та `endSlice`. Функція повинна повертати масив.
# --hints--
Використовуйте метод «`slice`» у своєму коді.
```js
assert(code.match(/\.slice/g));
```
Змінна `inputAnim` не повинна змінюватися.
```js
assert(
JSON.stringify(inputAnim) ===
JSON.stringify(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'])
);
```
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)` повинен повертатися як `["Dog", "Tiger"]`.
```js
assert(
JSON.stringify(sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 1, 3)) ===
JSON.stringify(['Dog', 'Tiger'])
);
```
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)` повинен повертатися як `["Cat"]`.
```js
assert(
JSON.stringify(sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 0, 1)) ===
JSON.stringify(['Cat'])
);
```
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4)` повинен повертатися як `["Dog", "Tiger", "Zebra"]`.
```js
assert(
JSON.stringify(sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 1, 4)) ===
JSON.stringify(['Dog', 'Tiger', 'Zebra'])
);
```
# --seed--
## --seed-contents--
```js
function sliceArray(anim, beginSlice, endSlice) {
// Only change code below this line
// Only change code above this line
}
const inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
sliceArray(inputAnim, 1, 3);
```
# --solutions--
```js
function sliceArray(anim, beginSlice, endSlice) {
return anim.slice(beginSlice, endSlice);
}
const inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
```

View File

@@ -0,0 +1,101 @@
---
id: 587d7da9367417b2b2512b69
title: Сортування масиву в алфавітному порядку за допомогою сортувального методу
challengeType: 1
forumTopicId: 18303
dashedName: sort-an-array-alphabetically-using-the-sort-method
---
# --description--
Метод `sort` сортує елементи масиву відповідно до функції зворотного зв'язку.
Наприклад:
```js
function ascendingOrder(arr) {
return arr.sort(function(a, b) {
return a - b;
});
}
ascendingOrder([1, 5, 2, 3, 4]);
```
Це б повернуло значення `[1, 2, 3, 4, 5]`.
```js
function reverseAlpha(arr) {
return arr.sort(function(a, b) {
return a === b ? 0 : a < b ? 1 : -1;
});
}
reverseAlpha(['l', 'h', 'z', 'b', 's']);
```
Це б повернуло значення `['z', 's', 'l', 'h', 'b']`.
Типовий метод сортування JavaScript полягає в сортуванні рядкових точок Unicode, що може видавати неочікувані результати. Таким чином, це заохотить виклик функції зворотнього зв'язку, що визначить порядок сортування об'єктів масиву. Коли подана така функція зворотного зв'язку, яка зазвичай називається `compareFunction`, то елементи масиву відсортовуються відповідно до зворотнього значення `compareFunction`: Якщо `compareFunction(a,b)` видає значення менше за 0 для двох елементів `a` і `b`, тоді `a` переміститься перед `b`. Якщо `compareFunction(a,b)` видає значення більше 0 для двох елементів `a` і `b`, тоді `b` переміститься перед `a`. Якщо `compareFunction(a,b)` видає значення рівне 0 для двох елементів `a` і `b`, то `a` і `b` залишаться без змін.
# --instructions--
Використовуйте метод `sort` у функції `alphabeticalOrder`, щоб відсортувати елементи `arr` в алфавітному порядку. Функція має повернути впорядкований масив.
# --hints--
Використовуйте метод `sort` у вашому коді.
```js
assert(code.match(/\.sort/g));
```
`alphabeticalOrder(["a", "d", "c", "a", "z", "g"])` має видати `["a", "a", "c", "d", "g", "z"]`.
```js
assert(
JSON.stringify(alphabeticalOrder(['a', 'd', 'c', 'a', 'z', 'g'])) ===
JSON.stringify(['a', 'a', 'c', 'd', 'g', 'z'])
);
```
`alphabeticalOrder(["x", "h", "a", "m", "n", "m"])` має видати `["a", "h", "m", "m", "n", "x"]`.
```js
assert(
JSON.stringify(alphabeticalOrder(['x', 'h', 'a', 'm', 'n', 'm'])) ===
JSON.stringify(['a', 'h', 'm', 'm', 'n', 'x'])
);
```
`alphabeticalOrder(["a", "a", "a", "a", "x", "t"])` має видати `["a", "a", "a", "a", "t", "x"]`.
```js
assert(
JSON.stringify(alphabeticalOrder(['a', 'a', 'a', 'a', 'x', 't'])) ===
JSON.stringify(['a', 'a', 'a', 'a', 't', 'x'])
);
```
# --seed--
## --seed-contents--
```js
function alphabeticalOrder(arr) {
// Only change code below this line
return arr
// Only change code above this line
}
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
```
# --solutions--
```js
function alphabeticalOrder(arr) {
return arr.sort();
}
```

View File

@@ -0,0 +1,87 @@
---
id: 587d7daa367417b2b2512b6b
title: Розділіть рядок на масив використовуючи метод split
challengeType: 1
forumTopicId: 18305
dashedName: split-a-string-into-an-array-using-the-split-method
---
# --description--
Метод `split` розділяє рядок на сукупність рядів. Для розділювача потрібен аргумент, який може бути символом для розбиття рядка або регулярного виразу. Наприклад, якщо роздільник це простір, ви отримаєте масив слів, і якщо роздільник є пустим рядком, ви отримаєте масив кожного символа у рядку.
Ось два приклади, які розділяють один рядок на пробіли, а потім інші на цифри, використовуючи регулярний вираз:
```js
const str = "Hello World";
const bySpace = str.split(" ");
const otherString = "How9are7you2today";
const byDigits = otherString.split(/\d/);
```
`bySpace` матиме значення `["Hello", "World"]` і `byDigits` матиме значення `["How", "are", "you", "today"]`.
Оскільки рядки незмінні, метод `split` полегшує роботу з ними.
# --instructions--
Використовуйте метод `split` усередині функції `splitify`, щоб розділити `str` на масив слів. Функція повинна повертати масив слів. Звернімо увагу, що слова не завжди розділені пробілами, а масив не повинен містити знаки пунктуації.
# --hints--
Ваш код повинен використовувати метод `split`.
```js
assert(code.match(/\.split/g));
```
`splitify("Hello World, I-am code")` має повертати <code["Hello", "World", "I", "am", "code"]</code>.
```js
assert(
JSON.stringify(splitify('Hello World,I-am code')) ===
JSON.stringify(['Hello', 'World', 'I', 'am', 'code'])
);
```
`splitify("Earth-is-our home")` має повертати `["Earth", "is", "our", "home"]`.
```js
assert(
JSON.stringify(splitify('Earth-is-our home')) ===
JSON.stringify(['Earth', 'is', 'our', 'home'])
);
```
`splitify("This.is.a-sentence")` має повертати `["This", "is", "a", "sentence"]`.
```js
assert(
JSON.stringify(splitify('This.is.a-sentence')) ===
JSON.stringify(['This', 'is', 'a', 'sentence'])
);
```
# --seed--
## --seed-contents--
```js
function splitify(str) {
// Only change code below this line
// Only change code above this line
}
splitify("Hello World,I-am code");
```
# --solutions--
```js
function splitify(str) {
return str.split(/\W/);
}
```

View File

@@ -0,0 +1,112 @@
---
id: 587d7b8e367417b2b2512b5c
title: Розуміння термінології функціонального програмування
challengeType: 1
forumTopicId: 301240
dashedName: understand-functional-programming-terminology
---
# --description--
Команда FCC мала поганий настрій і зараз хоче два види чаю: зелений і чорний. Загальновідомий факт: перепади настрою клієнта - це дуже поширене явище.
Володіючи такою інформацією, нам потрібно буде повторно ввести функцію `getTea` від останнього завдання для обробки різних чайних запитів. Ми можемо змінити `getTea`, щоб прийняти функцію як параметр для того, щоб мати можливість змінювати вид чаю, який готується. Це робить `getTea` більш гнучким, і надає програмісту більше контролю, коли клієнт просить щось змінити.
Та спершу, давайте розглянемо трохи функціональної термінології:
<dfn>Callbacks</dfn> - функції, які висуваються або передаються в іншу функцію, щоб з'ясувати посилання на цю функцію. Можливо, ви вже бачили як вони переходили до інших методів, наприклад в `filter`, функція зворотного виклику повідомляє для JavaScript критерії для фільтрування структурних даних.
Функції, що призначені для змінної, передані в іншу функцію, або навпаки повернені від іншої функції, так само як інше звичайне значення, називається функції <dfn>first class</dfn>. У JavaScript, всі функції - це функції першого класу.
Функції, що приймають функцію як аргумент, або повертають функцію як повернуте значення, називаються <dfn>higher order</dfn> функції.
Коли функції передаються або повертаються від іншої функції, тоді ті функції, які були передані або повернені, можуть називатися <dfn>lambda</dfn>.
# --instructions--
Приготуйте 27 чашок зеленого і 13 чашок чорного чаю і зберігайте їх відповідно у `tea4GreenTeamFCC` та `tea4BlackTeamFCC`. Зазначте, що функція `getTea` була змінена, тому тепер вона приймає функцію як перший аргумент.
Примітка: дані (кількість чашок чаю) надаються як останній аргумент. Ми поговоримо про це більше на подальших заняттях.
# --hints--
Змінна `tea4GreenTeamFCC` повинна мати 27 чашок зеленого чаю для команди.
```js
assert(tea4GreenTeamFCC.length === 27);
```
Змінна `tea4GreenTeamFCC` повинна мати чашки зеленого чаю.
```js
assert(tea4GreenTeamFCC[0] === 'greenTea');
```
Змінна `tea4BlackTeamFCC` повинна містити 13 чашок чорного чаю.
```js
assert(tea4BlackTeamFCC.length === 13);
```
Змінна `tea4BlackTeamFCC` повинна містити чашки з чорним чаєм.
```js
assert(tea4BlackTeamFCC[0] === 'blackTea');
```
# --seed--
## --seed-contents--
```js
// Function that returns a string representing a cup of green tea
const prepareGreenTea = () => 'greenTea';
// Function that returns a string representing a cup of black tea
const prepareBlackTea = () => 'blackTea';
/*
Given a function (representing the tea type) and number of cups needed, the
following function returns an array of strings (each representing a cup of
a specific type of tea).
*/
const getTea = (prepareTea, numOfCups) => {
const teaCups = [];
for(let cups = 1; cups <= numOfCups; cups += 1) {
const teaCup = prepareTea();
teaCups.push(teaCup);
}
return teaCups;
};
// Only change code below this line
const tea4GreenTeamFCC = null;
const tea4BlackTeamFCC = null;
// Only change code above this line
console.log(
tea4GreenTeamFCC,
tea4BlackTeamFCC
);
```
# --solutions--
```js
const prepareGreenTea = () => 'greenTea';
const prepareBlackTea = () => 'blackTea';
const getTea = (prepareTea, numOfCups) => {
const teaCups = [];
for(let cups = 1; cups <= numOfCups; cups += 1) {
const teaCup = prepareTea();
teaCups.push(teaCup);
}
return teaCups;
};
const tea4BlackTeamFCC = getTea(prepareBlackTea, 13);
const tea4GreenTeamFCC = getTea(prepareGreenTea, 27);
```

View File

@@ -0,0 +1,139 @@
---
id: 587d7b8e367417b2b2512b5d
title: Ризики використання Imperative Code
challengeType: 1
forumTopicId: 301241
dashedName: understand-the-hazards-of-using-imperative-code
---
# --description--
Функціональне програмування - хороша звичка. Це дозволяє вам легко керувати своїм кодом та рятує від підступних помилок. Але перед тим, як перейти до цього, варто розібрати імперативний метод програмування, щоб підкреслити моменти, з якими у вас можуть виникнути проблеми.
В англійській (та багатьох інших мовах) імператив використовується для надання команд. Так само у програмуванні імперативний стиль - це той, який надає комп'ютеру набір інструкцій, щоб виконати завдання.
Часто інструкції змінюють статус програми, як, наприклад, оновлення глобальних змінних. Типовий приклад - написання циклу `for`, який дає точні вказівки для ітерації по індексам масиву.
У той же час функціональне програмування - це форма декларативного програмування. Ви вказуєте комп'ютеру, що потрібно зробити, викликаючи метод чи функцію.
JavaScript пропонує багато попередньо визначених методів, які оброблюють загальні завдання. Тому вам не потрібно прописувати, як комп'ютер має виконати їх. Наприклад, замість використання циклу `for` згаданого вище, ви можете викликати метод `map`, який оброблює деталі ітерації по індексам масиву. Це допомагає уникнути смислових помилок, таких як, наприклад, "Помилка неврахованої одиниці", про які йшлося в розділі "Debugging".
Розглянемо ситуацію: ви переглядаєте веб-сторінки і хочете відслідковувати відкриті вкладки. Змоделюємо це, використовуючи звичайний об'єктно-орієнтований код.
Об'єкт Window складається з вкладок і, як правило, їх відкрито декілька. Назви кожного відкритого сайту в кожному об'єкті Window зберігаються в масиві. Після роботи в браузері (відкриття та закриття вкладок, об'єднанні вікон) ви хочете роздрукувати вкладки, які все ще відкриті. Закриті вкладки видаляються з масиву, а нові (для спрощення) додаються в кінець.
Редактор коду показує реалізацію цієї функціональності з функціями: `tabOpen()`, `tabClose()`, and `join()`. Масив `tabs` - це частина об'єкту Window, яка зберігає назви відкритих сторінок.
# --instructions--
Перевірте код у редакторі. Метод, який він використовує, має побічні ефекти у програмі та спричиняє некоректну поведінку. Остаточний список відкритих вкладок, збережених у `finalTabs.tabs`, має бути `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']`, але список, створений кодом, трохи відрізняється.
Змініть `Window.prototype.tabClose`, щоб видалити правильну вкладку.
# --hints--
`finalTabs.tabs` мають бути `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']`
```js
assert.deepEqual(finalTabs.tabs, [
'FB',
'Gitter',
'Reddit',
'Twitter',
'Medium',
'new tab',
'Netflix',
'YouTube',
'Vine',
'GMail',
'Work mail',
'Docs',
'freeCodeCamp',
'new tab'
]);
```
# --seed--
## --seed-contents--
```js
// tabs is an array of titles of each site open within the window
const Window = function(tabs) {
this.tabs = tabs; // We keep a record of the array inside the object
};
// When you join two windows into one window
Window.prototype.join = function(otherWindow) {
this.tabs = this.tabs.concat(otherWindow.tabs);
return this;
};
// When you open a new tab at the end
Window.prototype.tabOpen = function(tab) {
this.tabs.push('new tab'); // Let's open a new tab for now
return this;
};
// When you close a tab
Window.prototype.tabClose = function(index) {
// Only change code below this line
const tabsBeforeIndex = this.tabs.splice(0, index); // Get the tabs before the tab
const tabsAfterIndex = this.tabs.splice(index + 1); // Get the tabs after the tab
this.tabs = tabsBeforeIndex.concat(tabsAfterIndex); // Join them together
// Only change code above this line
return this;
};
// Let's create three browser windows
const workWindow = new Window(['GMail', 'Inbox', 'Work mail', 'Docs', 'freeCodeCamp']); // Your mailbox, drive, and other work sites
const socialWindow = new Window(['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium']); // Social sites
const videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']); // Entertainment sites
// Now perform the tab opening, closing, and other operations
const finalTabs = socialWindow
.tabOpen() // Open a new tab for cat memes
.join(videoWindow.tabClose(2)) // Close third tab in video window, and join
.join(workWindow.tabClose(1).tabOpen());
console.log(finalTabs.tabs);
```
# --solutions--
```js
const Window = function(tabs) {
this.tabs = tabs;
};
Window.prototype.join = function(otherWindow) {
this.tabs = this.tabs.concat(otherWindow.tabs);
return this;
};
Window.prototype.tabOpen = function(tab) {
this.tabs.push('new tab');
return this;
};
Window.prototype.tabClose = function(index) {
const tabsBeforeIndex = this.tabs.slice(0, index);
const tabsAfterIndex = this.tabs.slice(index + 1);
this.tabs = tabsBeforeIndex.concat(tabsAfterIndex);
return this;
};
const workWindow = new Window(['GMail', 'Inbox', 'Work mail', 'Docs', 'freeCodeCamp']);
const socialWindow = new Window(['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium']);
const videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']);
const finalTabs = socialWindow
.tabOpen()
.join(videoWindow.tabClose(2))
.join(workWindow.tabClose(1).tabOpen());
```

View File

@@ -0,0 +1,97 @@
---
id: 587d7b88367417b2b2512b45
title: 'Використовуйте функції вищого порядку map, filter або reduce для розв''язання складних проблем'
challengeType: 1
forumTopicId: 301311
dashedName: use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-problem
---
# --description--
Тепер, коли ви розв'язали кілька проблем, використовуючи такі функції вищого порядку, як: `map()`, `filter()`, та `reduce()`, ви можете застосовувати їх для виконання складнішого завдання.
# --instructions--
Завершіть код для функції `squareList` за допомогою комбінації `map()`, `filter()`, і `reduce()`. Функція має повернути новий масив, який містить квадрати *only* цілих натуральних чисел (десяткові числа не є цілими числами), коли до неї передається масив дійсних чисел. Приклад масиву дійсних чисел - `[-3, 4.8, 5, 3, -3.2]`.
**Примітка:** Ваша функція не повинна використовувати будь-які цикли `for` або `while`, або функцію `forEach()`.
# --hints--
`squareList` має бути `function`.
```js
assert.typeOf(squareList, 'function'),
'<code>squareList</code> should be a <code>function</code>';
```
Не слід використовувати `for`, `while` та `forEach`.
```js
assert(!code.match(/for|while|forEach/g));
```
Слід використовувати `map`, `filter` або `reduce`.
```js
assert(
__helpers
.removeWhiteSpace(code)
.match(/\.(map|filter|reduce)\(/g)
);
```
Функція має повертати `array`.
```js
assert(Array.isArray(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])));
```
`squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])` має повертати `[16, 1764, 36]`.
```js
assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [
16,
1764,
36
]);
```
`squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3])` має повертати `[9, 100, 49]`.
```js
assert.deepStrictEqual(squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3]), [
9,
100,
49
]);
```
# --seed--
## --seed-contents--
```js
const squareList = arr => {
// Only change code below this line
return arr;
// Only change code above this line
};
const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);
console.log(squaredIntegers);
```
# --solutions--
```js
const squareList = arr => {
const positiveIntegers = arr.filter(num => {
return num >= 0 && Number.isInteger(num);
});
const squaredIntegers = positiveIntegers.map(num => {
return num ** 2;
});
return squaredIntegers;
};
```

View File

@@ -0,0 +1,76 @@
---
id: 587d7dab367417b2b2512b6e
title: Використовуйте кожен метод, щоб перевірити, чи кожний елемент у масиві відповідає критеріям
challengeType: 1
forumTopicId: 301312
dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria
---
# --description--
Метод `every` працює з масивами, щоб перевірити, чи проходить елемент *every* певний тест. Якщо всі значення відповідають критеріям, то він повертає булеве значення `true`, якщо ж ні, тоді - `false`.
Наприклад, наступний код перевіряє чи кожен елемент в масиві `numbers` менший за 10:
```js
const numbers = [1, 5, 8, 0, 10, 11];
numbers.every(function(currentValue) {
return currentValue < 10;
});
```
В цьому випадку метод `every` поверне `false`.
# --instructions--
Використовуйте метод `every` всередині функції `checkPositive`, щоб перевірити, чи кожний елемент у `arr` додатній. Функція має повернути булеве значення.
# --hints--
Використовуйте у коді метод `every`.
```js
assert(code.match(/\.every/g));
```
`checkPositive([1, 2, 3, -4, 5])` має повернути `false`.
```js
assert.isFalse(checkPositive([1, 2, 3, -4, 5]));
```
`checkPositive([1, 2, 3, 4, 5])` має повернути `true`.
```js
assert.isTrue(checkPositive([1, 2, 3, 4, 5]));
```
`checkPositive([1, -2, 3, -4, 5])` має повернути `false`.
```js
assert.isFalse(checkPositive([1, -2, 3, -4, 5]));
```
# --seed--
## --seed-contents--
```js
function checkPositive(arr) {
// Only change code below this line
// Only change code above this line
}
checkPositive([1, 2, 3, -4, 5]);
```
# --solutions--
```js
function checkPositive(arr) {
return arr.every(num => num > 0);
}
```

View File

@@ -0,0 +1,314 @@
---
id: 587d7b8f367417b2b2512b63
title: Використовуйте метод фільтру, щоб отримати дані з сукупності елементів
challengeType: 1
forumTopicId: 18179
dashedName: use-the-filter-method-to-extract-data-from-an-array
---
# --description--
Інша зручна формула масиву є `Array.prototype.filter()`, або ж просто `filter()`.
`filter` викликає функцію в кожному елементі масиву й повертає новий масив, що містить в собі ті елементи, що повертає функція `true`. Іншими словами, він фільтрує масив, на основі функції, яка передана до нього. Як і `map`, це робиться без необхідності зміни початкового масиву.
Функція зворотнього виклику приймає три аргументи. Перший аргумент - це поточний елемент, який опрацьовується. Другий є індексом цього елемента, а третій - масивом, на якому було викликано метод `filter`.
Нижче наведено приклад використання методу `filter` у масиві `users` для повернення нового масиву, що містить лише імена користувачів віком до 30 років. Для простоти у прикладі використовується лише перший аргумент зворотного виклику.
```js
const users = [
{ name: 'John', age: 34 },
{ name: 'Amy', age: 20 },
{ name: 'camperCat', age: 10 }
];
const usersUnder30 = users.filter(user => user.age < 30);
console.log(usersUnder30);
```
Консоль відображатиме значення `[ { name: 'Amy', age: 20 }, { name: 'camperCat', age: 10 } ]`.
# --instructions--
Змінний `watchList` утримує масив об'єктів з інформацією про декілька фільмів. Використовуйте комбінацію `filter` and `map` на `watchList`, щоб задати новий масив об'єктів тільки з ключами доступу `title` і `rating`. Новий масив повинен включати в себе лише об’єкти, де `imdbRating` більше або дорівнює 8.0. Зверніть увагу, що значення `rating` збережено як рядки у об'єкті і вам може знадобитися конвертувати їх на числа для виконання математичних операцій з ними.
# --hints--
Змінний `watchList` не повинен змінюватись.
```js
assert(
watchList[0].Title === 'Inception' && watchList[4].Director == 'James Cameron'
);
```
Ваш код повинен використовувати метод `filter`.
```js
assert(code.match(/\s*\.\s*filter/g));
```
Ваш код не повинен використовувати цикл `for`.
```js
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
```
`filteredList` має дорівнювати `[{"title": "Inception", "rating": "8.8"}, {"title": "Interstellar", "rating": "8.6"}, {"title": "The Dark Knight", "rating": "9.0"}, {"title": "Batman Begins", "rating": "8.3"}]`.
```js
assert.deepEqual(filteredList, [
{ title: 'Inception', rating: '8.8' },
{ title: 'Interstellar', rating: '8.6' },
{ title: 'The Dark Knight', rating: '9.0' },
{ title: 'Batman Begins', rating: '8.3' }
]);
```
# --seed--
## --seed-contents--
```js
// The global variable
const watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Elliot Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
// Only change code below this line
const filteredList = "";
// Only change code above this line
console.log(filteredList);
```
# --solutions--
```js
const watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Elliot Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
const filteredList = watchList.filter(e => e.imdbRating >= 8).map( ({Title: title, imdbRating: rating}) => ({title, rating}) );
```

View File

@@ -0,0 +1,329 @@
---
id: 587d7b8f367417b2b2512b61
title: Використовувати метод map для отримання даних з масиву
challengeType: 1
forumTopicId: 18214
dashedName: use-the-map-method-to-extract-data-from-an-array
---
# --description--
Поки що ми навчилися використовувати чисті функції, щоб уникати побічних ефектів в програмі. Крім того, ми побачили, що значення функції залежить тільки від її вхідних аргументів.
Це лише початок. Як випливає з назви, функціональне програмування зосереджено навколо теорії функцій.
Мало б сенс мати можливість передати їх в якості аргументів інших функцій, і повернути з іншої функції. Функції вважаються <dfn> об’єктами першого класу </dfn> у JavaScript і означає, що вони можуть бути використані як і будь -який інший об’єкт. Вони можуть бути збережені у змінних, що зберігаються в об'єкті або передаються у вигляді аргументів функції.
Почнемо з деяких простих функцій масиву, які є методами об'єкта масиву прототипу. У цій вправі ми розглядаємо `Array.prototype.map()`, або простіше кажучи `map`.
Метод `map` перебирає кожен елемент у масиві та повертає новий масив, що містить результати функції зворотного виклику для кожного елемента. Це виконується без мутації вихідного масиву.
При використанні зворотного виклику передається три аргументи. Перший аргумент є поточним елементом який обробляється. Другий - індекс цього елемента, а третій - масив, на якому є так званий метод`map`.
Нижче наведено приклад використання методу `map` у масиві `users` для повернення нового масиву, що містить лише імена користувачів в якості елементів. Для простоти у прикладі використовується лише перший аргумент функції зворотного виклику.
```js
const users = [
{ name: 'John', age: 34 },
{ name: 'Amy', age: 20 },
{ name: 'camperCat', age: 10 }
];
const names = users.map(user => user.name);
console.log(names);
```
На консолі відображатиметься значення `['John', 'Amy','camperCat']`.
# --instructions--
Масив `watchList` містить об’єкти з інформацією про декілька фільмів. Використовуйте `map` у `watchList`, щоб призначити новий масив об’єктів до `ratings`змінної. Кожен фільм у новому масиві повинен мати лише ключ `title` з назвою фільму та ключ `rating` з рейтингом IMDB. В редакторі зараз використовується цикл `for`, тому слід замінити функціональність циклу виразом `map`.
# --hints--
Змінна `watchList` не повинна змінюватися.
```js
assert(
watchList[0].Title === 'Inception' && watchList[4].Director == 'James Cameron'
);
```
Ваш код не повинен використовувати цикл `for`цикл.
```js
assert(!code.match(/for\s*?\([\s\S]*?\)/));
```
Ваш код повинен використовувати метод `map`.
```js
assert(code.match(/\.map/g));
```
`ratings` має дорівнювати `[{"title": "Inception", "rating": "8.8"}, {"title": "Interstellar", "rating": "8.6"}, {"title": "The Dark Knight", "rating": "9.0"},{"title": "Batman Begins", "rating": "8.3"}, {"title": "Avatar", "rating": "7.9"}]`.
```js
assert.deepEqual(ratings, [
{ title: 'Inception', rating: '8.8' },
{ title: 'Interstellar', rating: '8.6' },
{ title: 'The Dark Knight', rating: '9.0' },
{ title: 'Batman Begins', rating: '8.3' },
{ title: 'Avatar', rating: '7.9' }
]);
```
# --seed--
## --seed-contents--
```js
// The global variable
const watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Elliot Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
// Only change code below this line
const ratings = [];
for (let i = 0; i < watchList.length; i++) {
ratings.push({title: watchList[i]["Title"], rating: watchList[i]["imdbRating"]});
}
// Only change code above this line
console.log(JSON.stringify(ratings));
```
# --solutions--
```js
const watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Elliot Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
const ratings = watchList.map(function(movie) {
return {
title: movie["Title"],
rating: movie["imdbRating"]
}
});
```

View File

@@ -0,0 +1,345 @@
---
id: 587d7da9367417b2b2512b68
title: Використовуйте метод reduce для аналізу даних
challengeType: 1
forumTopicId: 301313
dashedName: use-the-reduce-method-to-analyze-data
---
# --description--
`Array.prototype.reduce()` або просто `reduce()` - це найзагальніша з усіх операцій з масивами в JavaScript. Ви можете вирішити практично будь -яку проблему з обробкою масиву, використовуючи метод `reduce`.
Метод `reduce` дозволяє використовувати більш загальні форми обробки масивів, і можна показати, що і `filter`, і `map` можуть бути отримані як спеціальні програми `reduce`. Метод `reduce` перебирає кожен елемент у масиві та повертає єдине значення (тобто рядок, число, об’єкт, масив). Це досягається за допомогою функції зворотного виклику, яка відбувається на кожній ітерації.
Функція зворотного виклику приймає чотири аргументи. Перший аргумент відомий як акумулятор, якому призначається повернене значення функції зворотного виклику з попередньої ітерації, другий - поточний елемент, що обробляється, третій - індекс цього елемента, а четвертий - масив, < code>reduce</code> на який звернений виклик.
На додаток до функції зворотного виклику, `reduce` має додатковий параметр, який приймає початкове значення для підсумовуюючого регістру. Якщо цей другий параметр не використовується, то перша ітерація пропускається, а друга передається першому елементу масиву як акумулятору.
Нижче наведено приклад використання `reduce` у масиві `users`, щоб повернути суму всіх вікових категорій користувачів. Для простоти у прикладі використовуються лише перший і другий аргументи.
```js
const users = [
{ name: 'John', age: 34 },
{ name: 'Amy', age: 20 },
{ name: 'camperCat', age: 10 }
];
const sumOfAges = users.reduce((sum, user) => sum + user.age, 0);
console.log(sumOfAges);
```
На консолі відображатиметься значення `64`.
В іншому прикладі можна побачити, як об'єкт може бути повернутий, що містить імена користувачів, які становлять таку ж цінність як і властивості щодо їх віку.
```js
const users = [
{ name: 'John', age: 34 },
{ name: 'Amy', age: 20 },
{ name: 'camperCat', age: 10 }
];
const usersObj = users.reduce((obj, user) => {
obj[user.name] = user.age;
return obj;
}, {});
console.log(usersObj);
```
На консолі відображатиметься значення `{John: 34, Amy: 20, camperCat: 10}`.
# --instructions--
Змінна `watchList` містить масив об’єктів з інформацією щодо декількох фільмів. Використовуйте `reduce`, щоб знайти середній рейтинг IMDB фільмів режисера `Крістофера Нолана`. Пригадайте з попередніх проблем, як дані `filter` та `map` можуть витягнути те, що нам потрібно. Можливо, доведеться створити інші змінні та повернути середній рейтинг із функції `getRating`. Зверніть увагу, що рейтингові значення зберігаються як рядки в об’єкті і їх потрібно перетворити в числа перш ніж вони будуть використані в будь-яких математичних операціях.
# --hints--
Змінна `watchList` не повинна змінюватися.
```js
assert(
watchList[0].Title === 'Inception' && watchList[4].Director == 'James Cameron'
);
```
Ваш код повинен використовувати метод `reduce`.
```js
assert(code.match(/\.reduce/g));
```
`getRating(watchList)` має дорівнювати 8.675.
```js
assert(getRating(watchList) === 8.675);
```
Ваш код не повинен використовувати цикл `for`.
```js
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
```
Ваш код повинен повернути правильний висновок після зміни об’єкта `watchList`.
```js
assert(getRating(watchList.filter((_, i) => i < 1 || i > 2)) === 8.55);
```
# --seed--
## --seed-contents--
```js
// The global variable
const watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Elliot Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
function getRating(watchList) {
// Only change code below this line
let averageRating;
// Only change code above this line
return averageRating;
}
console.log(getRating(watchList));
```
# --solutions--
```js
const watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Elliot Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
function getRating(watchList) {
let averageRating;
const rating = watchList
.filter(obj => obj.Director === "Christopher Nolan")
.map(obj => Number(obj.imdbRating));
averageRating = rating.reduce((accum, curr) => accum + curr)/rating.length;
return averageRating;
}
```

View File

@@ -0,0 +1,76 @@
---
id: 587d7dab367417b2b2512b6f
title: Використовуйте метод some, щоб перевірити, чи будь-які елементи в масиві відповідають критеріям
challengeType: 1
forumTopicId: 301314
dashedName: use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria
---
# --description--
Метод `some` працює з масивами, щоб перевірити, чи проходить елемент *any* певний тест. Якщо будь-яке зі значень відповідає критеріям, то він повертає булеве значення `true`, якщо ж ні, тоді - `false`.
Наприклад, наступний код перевіряє чи будь-який елемент в масиві `numbers` менший за 10:
```js
const numbers = [10, 50, 8, 220, 110, 11];
numbers.some(function(currentValue) {
return currentValue < 10;
});
```
Метод `some` поверне `true`.
# --instructions--
Використовуйте метод `some` всередині функції `checkPositive`, щоб перевірити, чи будь-який елемент у `arr` додатній. Функція має повернути булеве значення.
# --hints--
Використовуйте у коді метод `some`.
```js
assert(code.match(/\.some/g));
```
`checkPositive([1, 2, 3, -4, 5])` має повернути `true`.
```js
assert(checkPositive([1, 2, 3, -4, 5]));
```
`checkPositive([1, 2, 3, 4, 5])` має повернути `true`.
```js
assert(checkPositive([1, 2, 3, 4, 5]));
```
`checkPositive([-1, -2, -3, -4, -5])` має повернути `false`.
```js
assert(!checkPositive([-1, -2, -3, -4, -5]));
```
# --seed--
## --seed-contents--
```js
function checkPositive(arr) {
// Only change code below this line
// Only change code above this line
}
checkPositive([1, 2, 3, -4, 5]);
```
# --solutions--
```js
function checkPositive(arr) {
return arr.some(elem => elem > 0);
}
```