├── .gitignore ├── .markdownlint.yaml ├── .prettierrc.json ├── README.md ├── lesson-01 ├── en.md ├── es.md ├── ru.md └── uk.md ├── lesson-02 ├── en.md ├── es.md ├── ru.md └── uk.md ├── lesson-03 ├── en.md ├── es.md ├── ru.md └── uk.md ├── lesson-04 ├── en.md ├── es.md ├── ru.md └── uk.md ├── lesson-05 ├── en.md ├── es.md ├── ru.md └── uk.md ├── lesson-06 ├── en.md ├── es.md ├── ru.md └── uk.md ├── lesson-07 ├── en.md ├── es.md ├── ru.md └── uk.md ├── lesson-08 ├── en.md ├── es.md ├── ru.md └── uk.md ├── lesson-09 ├── en.md ├── es.md ├── ru.md └── uk.md └── lesson-10 ├── en.md ├── es.md ├── ru.md └── uk.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .vscode 3 | stash.md 4 | app.js -------------------------------------------------------------------------------- /.markdownlint.yaml: -------------------------------------------------------------------------------- 1 | MD024: false 2 | MD033: false 3 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 80, 3 | "tabWidth": 2, 4 | "useTabs": false, 5 | "semi": true, 6 | "singleQuote": true, 7 | "trailingComma": "es5", 8 | "bracketSpacing": true, 9 | "jsxBracketSameLine": false, 10 | "arrowParens": "avoid", 11 | "proseWrap": "always" 12 | } 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # js-instructor-examples 2 | -------------------------------------------------------------------------------- /lesson-01/en.md: -------------------------------------------------------------------------------- 1 | # Module 1. Lesson 1. Variables, types and operators 2 | 3 | ## Example 1 - Mathematical operators 4 | 5 | Display the total number of apples and grapes on the screen. The difference between apples and grapes. 6 | 7 | ```js 8 | const apples = 47; 9 | const grapes = 135; 10 | const total = ; 11 | console.log(total) 12 | const diff = ; 13 | console.log(diff) 14 | ``` 15 | 16 | ## Example 2 - Combined operators 17 | 18 | Replace the override expression with the combined operator `+=`. 19 | 20 | ```js 21 | let students = 100; 22 | students = students + 50; 23 | console.log(students); 24 | ``` 25 | 26 | ## Example 3 - Operators Priority 27 | 28 | Disassemble operators priority in the variable value assignment instruction 29 | `result`. 30 | 31 | ```js 32 | const result = 108 + 223 - 2 * 5; 33 | console.log(result); 34 | ``` 35 | 36 | ## Example 4 - Math class 37 | 38 | Write a script that prints to the console rounded up/down, etc. values 39 | of variable `value`. Use the methods `Math.floor()`, `Math.ceil()` and 40 | `Math.round()`. Check what happens in the console for the values "27.3" and "27.9". 41 | 42 | ```js 43 | const value = 27.5; 44 | ``` 45 | 46 | ## Example 5 - Template lines 47 | 48 | Compose a phrase using the template strings `A has B bots in stock`, where A, B - 49 | variables inserted into a line. 50 | 51 | ```js 52 | const companyName = 'Cyberdyne Systems'; 53 | const repairBots = 150; 54 | const defenceBots = 50; 55 | const message = ``; 56 | console.log(message); // "Cyberdyne Systems has 200 bots in stock" 57 | ``` 58 | 59 | ## Example 6 - String methods and chaining 60 | 61 | Write a script that calculates a person's body mass index. For this 62 | you need to divide the weight in kilograms by the square of the person's height in meters. 63 | 64 | Weight and height are stored in the `weight` and `height` variables, but not as numbers, but in 65 | as strings (specially for the task). Non-integer numbers can be given as 66 | `24.7` or `24,7`,that is, as a separator of the fractional part can be 67 | comma. 68 | 69 | The body mass index should be rounded to one decimal place; 70 | 71 | ```js 72 | let weight = '88,3'; 73 | let height = '1.75'; 74 | 75 | const bmi = ; 76 | console.log(bmi); // 28.8 77 | ``` 78 | 79 | ## Example 7 - Comparison operators and type casting 80 | 81 | What will be the result of the expressions? 82 | 83 | ```js 84 | console.log(5 > 4); 85 | 86 | console.log(10 >= '7'); 87 | 88 | console.log('2' > '12'); 89 | 90 | console.log('2' < '12'); 91 | 92 | console.log('4' == 4); 93 | 94 | console.log('6' === 6); 95 | 96 | console.log('false' === false); 97 | 98 | console.log(1 == true); 99 | 100 | console.log(1 === true); 101 | 102 | console.log('0' == false); 103 | 104 | console.log('0' === false); 105 | 106 | console.log('Papaya' < 'papaya'); 107 | 108 | console.log('Papaya' === 'papaya'); 109 | 110 | console.log(undefined == null); 111 | 112 | console.log(undefined === null); 113 | ``` 114 | 115 | ## Example 8 - Logical operators 116 | 117 | What will be the result of the expressions? 118 | 119 | ```js 120 | console.log(true && 3); 121 | 122 | console.log(false && 3); 123 | 124 | console.log(true && 4 && 'kiwi'); 125 | 126 | console.log(true && 0 && 'kiwi'); 127 | 128 | console.log(true || 3); 129 | 130 | console.log(true || 3 || 4); 131 | 132 | console.log(true || false || 7); 133 | 134 | console.log(null || 2 || undefined); 135 | 136 | console.log((1 && null && 2) > 0); 137 | 138 | console.log(null || (2 && 3) || 4); 139 | ``` 140 | 141 | ## Example 9 - Default value and null merge operator 142 | 143 | Refactor the code so that the value is assigned to the `value` variable 144 | variable `incomingValue` if it is not equal to `undefined` or `null`. Otherwise, 145 | `defaultValue` must be assigned. Check work 146 | script for the following values of the `incomingValue` variable: null, undefined, 0, 147 | false. Use operator `??` (nullish coalescing operator). 148 | 149 | ```js 150 | const incomingValue = 5; 151 | const defaultValue = 10; 152 | const value = incomingValue || defaultValue; 153 | console.log(value); 154 | ``` 155 | 156 | ## Example 10 - The % Operator and String Methods 157 | 158 | Write a script that will convert the value of `totalMinutes` (number of minutes) to 159 | string in hour and minute format `HH:MM`. 160 | 161 | - 70 will show 01:10 162 | - 450 will show 07:30 163 | - 1441 will show 24:01 164 | 165 | ```js 166 | const totalMinutes = 70; 167 | 168 | const hours = Math.floor(totalMinutes / 60); 169 | const minutes = totalMinutes % 60; 170 | console.log(hours); 171 | console.log(minutes); 172 | 173 | const doubleDigitHours = String(hours).padStart(2, 0); 174 | const doubleDigitMinutes = String(minutes).padStart(2, 0); 175 | console.log(`${doubleDigitHours}:${doubleDigitMinutes}`); 176 | ``` 177 | -------------------------------------------------------------------------------- /lesson-01/es.md: -------------------------------------------------------------------------------- 1 | # Módulo 1. Clase 1. Variables, tipos y operadores 2 | 3 | ## Ejemplo 1 - Operadores matemáticos 4 | 5 | Muestra el número total de manzanas y uvas. La diferencia entre las manzanas y las uvas. 6 | 7 | ```js 8 | const apples = 47; 9 | const grapes = 135; 10 | const total = ; 11 | console.log(total) 12 | const diff = ; 13 | console.log(diff) 14 | ``` 15 | 16 | ## Ejemplo 2 - Operadores combinados 17 | 18 | Sustituye la expresión de redefinición por el operador combinado `+=`. 19 | 20 | ```js 21 | let students = 100; 22 | students = students + 50; 23 | console.log(students); 24 | ``` 25 | 26 | ## Example 3 - Prioridad de los operadores 27 | 28 | Analiza la prioridad de los operadores, en la instrucción para asignar un valor a la variable `result`. 29 | 30 | ```js 31 | const result = 108 + 223 - 2 * 5; 32 | console.log(result); 33 | ``` 34 | 35 | ## Ejemplo 4 - Clase Math 36 | 37 | Escriba un script que muestre en la consola los valores redondeados hacia abajo/arriba, etc. 38 | de la variable `value`. Use los métodos `Math.floor()`, `Math.ceil()` y `Math.round()`. 39 | Comprueba lo que aparece en la consola con los valores `27.3` y `27.9`. 40 | 41 | ```js 42 | const value = 27.5; 43 | ``` 44 | 45 | ## Ejemplo 5 - Plantilla de cadena 46 | 47 | Escriba una frase utilizando una plantilla de cadena `A has B bots in stock`, donde A, B 48 | son variables insertadas en la cadena. 49 | 50 | ```js 51 | const companyName = 'Cyberdyne Systems'; 52 | const repairBots = 150; 53 | const defenceBots = 50; 54 | const message = ``; 55 | console.log(message); // "Cyberdyne Systems has 200 bots in stock" 56 | ``` 57 | 58 | ## Ejemplo 6 - Métodos de cadenas y encadenamiento 59 | 60 | Escriba un script que calcule el índice de masa corporal de una persona. Para ello 61 | divide el peso en kilogramos por el cuadrado de la altura de la persona en metros. 62 | 63 | El peso y la altura se almacenan en las variables `weight` y `height`, pero no como 64 | números, sino como cadenas (específicamente para esta tarea). Los números no enteros se 65 | pueden dar en forma de `24.7` o `24,7`, es decir, la parte de la fracción puede estar 66 | separada por una coma. 67 | 68 | El índice de masa corporal debe redondearse para que tenga solo una cifra después de la coma; 69 | 70 | ```js 71 | let weight = '88,3'; 72 | let height = '1.75'; 73 | 74 | const bmi = ; 75 | console.log(bmi); // 28.8 76 | ``` 77 | 78 | ## Ejemplo 7 - Operadores de comparación y conversión de tipos 79 | 80 | ¿Cuál sería el resultado de las expresiones? 81 | 82 | ```js 83 | console.log(5 > 4); 84 | 85 | console.log(10 >= '7'); 86 | 87 | console.log('2' > '12'); 88 | 89 | console.log('2' < '12'); 90 | 91 | console.log('4' == 4); 92 | 93 | console.log('6' === 6); 94 | 95 | console.log('false' === false); 96 | 97 | console.log(1 == true); 98 | 99 | console.log(1 === true); 100 | 101 | console.log('0' == false); 102 | 103 | console.log('0' === false); 104 | 105 | console.log('Papaya' < 'papaya'); 106 | 107 | console.log('Papaya' === 'papaya'); 108 | 109 | console.log(undefined == null); 110 | 111 | console.log(undefined === null); 112 | ``` 113 | 114 | ## Ejemplo 8 - Operadores lógicos 115 | 116 | ¿Cuál sería el resultado de las expresiones? 117 | 118 | ```js 119 | console.log(true && 3); 120 | 121 | console.log(false && 3); 122 | 123 | console.log(true && 4 && 'kiwi'); 124 | 125 | console.log(true && 0 && 'kiwi'); 126 | 127 | console.log(true || 3); 128 | 129 | console.log(true || 3 || 4); 130 | 131 | console.log(true || false || 7); 132 | 133 | console.log(null || 2 || undefined); 134 | 135 | console.log((1 && null && 2) > 0); 136 | 137 | console.log(null || (2 && 3) || 4); 138 | ``` 139 | 140 | ## Ejemplo 9 - Valor por defecto y Nullish coalescing operator 141 | 142 | Refactoriza el código para que a la variable `value` se le asigne el valor de 143 | la variable `incomingValue` , en caso de que el valor no sea `undefined` o `null`. 144 | En caso contrario, se debe asignar el valor `defaultValue`. Comprueba que el script 145 | funciona para los siguientes valores de la variable `incomingValue`: null, undefined, 146 | 0, false. Utilice el operador `??` (nullish coalescing operator). 147 | 148 | ```js 149 | const incomingValue = 5; 150 | const defaultValue = 10; 151 | const value = incomingValue || defaultValue; 152 | console.log(value); 153 | ``` 154 | 155 | ## Ejemplo 10 - Operador % y métodos de cadena 156 | 157 | Escribe un script que traduzca el valor de `totalMinutes` ( cantidad de minutos) en 158 | una cadena en formato de horas y minutos `HH:MM`. 159 | 160 | - 70 muestra 01:10 161 | - 450 muestra 07:30 162 | - 1441 muestra 24:01 163 | 164 | ```js 165 | const totalMinutes = 70; 166 | 167 | const hours = Math.floor(totalMinutes / 60); 168 | const minutes = totalMinutes % 60; 169 | console.log(hours); 170 | console.log(minutes); 171 | 172 | const doubleDigitHours = String(hours).padStart(2, 0); 173 | const doubleDigitMinutes = String(minutes).padStart(2, 0); 174 | console.log(`${doubleDigitHours}:${doubleDigitMinutes}`); 175 | ``` 176 | -------------------------------------------------------------------------------- /lesson-01/ru.md: -------------------------------------------------------------------------------- 1 | # Модуль 1. Занятие 1. Переменные, типы и операторы 2 | 3 | ## Example 1 - Математические операторы 4 | 5 | Выведи на экран общее количество яблок и винограда. Разницу яблок и винограда. 6 | 7 | ```js 8 | const apples = 47; 9 | const grapes = 135; 10 | const total = ; 11 | console.log(total) 12 | const diff = ; 13 | console.log(diff) 14 | ``` 15 | 16 | ## Example 2 - Комбинированные операторы 17 | 18 | Замени выражение переопределения комбинированным оператором `+=`. 19 | 20 | ```js 21 | let students = 100; 22 | students = students + 50; 23 | console.log(students); 24 | ``` 25 | 26 | ## Example 3 - Приоритет операторов 27 | 28 | Разбери приоритет операторов в инструкции присвоения значения переменной 29 | `result`. 30 | 31 | ```js 32 | const result = 108 + 223 - 2 * 5; 33 | console.log(result); 34 | ``` 35 | 36 | ## Example 4 - Класс Math 37 | 38 | Напиши скрипт, который выводит в консоль округленные вверх/вниз и т.д. значения 39 | переменной `value`. Используй методы `Math.floor()`, `Math.ceil()` и 40 | `Math.round()`. Проверь что будет в консоли при значениях `27.3` и `27.9`. 41 | 42 | ```js 43 | const value = 27.5; 44 | ``` 45 | 46 | ## Example 5 - Шаблонные строки 47 | 48 | Составь фразу с помощью шаблонных строк `A has B bots in stock`, где A, B - 49 | переменные вставленные в строку. 50 | 51 | ```js 52 | const companyName = 'Cyberdyne Systems'; 53 | const repairBots = 150; 54 | const defenceBots = 50; 55 | const message = ``; 56 | console.log(message); // "Cyberdyne Systems has 200 bots in stock" 57 | ``` 58 | 59 | ## Example 6 - Методы строк и чейнинг 60 | 61 | Напиши скрипт который рассчитывает индекс массы тела человека. Для этого 62 | необходимо разделить вес в киллограммах на квадрат высоты человека в метрах. 63 | 64 | Вес и высота хранятся в переменных `weight` и `height`, но не как числа, а в 65 | виде строк (специально для задачи). Нецелые числа могут быть заданы в виде 66 | `24.7` или `24,7`, то есть в качестве разделителя дробной части может быть 67 | запятая. 68 | 69 | Индекс массиы тела необходимо округлить до одной цифры после запятой; 70 | 71 | ```js 72 | let weight = '88,3'; 73 | let height = '1.75'; 74 | 75 | const bmi = ; 76 | console.log(bmi); // 28.8 77 | ``` 78 | 79 | ## Example 7 - Операторы сравнения и приведение типов 80 | 81 | Каким будет результат выражений? 82 | 83 | ```js 84 | console.log(5 > 4); 85 | 86 | console.log(10 >= '7'); 87 | 88 | console.log('2' > '12'); 89 | 90 | console.log('2' < '12'); 91 | 92 | console.log('4' == 4); 93 | 94 | console.log('6' === 6); 95 | 96 | console.log('false' === false); 97 | 98 | console.log(1 == true); 99 | 100 | console.log(1 === true); 101 | 102 | console.log('0' == false); 103 | 104 | console.log('0' === false); 105 | 106 | console.log('Papaya' < 'papaya'); 107 | 108 | console.log('Papaya' === 'papaya'); 109 | 110 | console.log(undefined == null); 111 | 112 | console.log(undefined === null); 113 | ``` 114 | 115 | ## Example 8 - Логические операторы 116 | 117 | Каким будет результат выражений? 118 | 119 | ```js 120 | console.log(true && 3); 121 | 122 | console.log(false && 3); 123 | 124 | console.log(true && 4 && 'kiwi'); 125 | 126 | console.log(true && 0 && 'kiwi'); 127 | 128 | console.log(true || 3); 129 | 130 | console.log(true || 3 || 4); 131 | 132 | console.log(true || false || 7); 133 | 134 | console.log(null || 2 || undefined); 135 | 136 | console.log((1 && null && 2) > 0); 137 | 138 | console.log(null || (2 && 3) || 4); 139 | ``` 140 | 141 | ## Example 9 - Значение по умолчанию и оператор нулевого слияния 142 | 143 | Отрефактори код так, чтобы в переменную `value` присваивалось значение 144 | переменной `incomingValue`, если оно не равно `undefined` или `null`. В 145 | противном случае должно присваиваться значение `defaultValue`. Проверь работу 146 | скрипта для слепдующих значений переменной `incomingValue`: null, undefined, 0, 147 | false. Используй оператор `??` (nullish coalescing operator). 148 | 149 | ```js 150 | const incomingValue = 5; 151 | const defaultValue = 10; 152 | const value = incomingValue || defaultValue; 153 | console.log(value); 154 | ``` 155 | 156 | ## Example 10 - Опертор % и методы строк 157 | 158 | Напиши скрипт который переведёт значение `totalMinutes` (количество минут) в 159 | строку в формате часов и минут `HH:MM`. 160 | 161 | - 70 покажет 01:10 162 | - 450 покажет 07:30 163 | - 1441 покажет 24:01 164 | 165 | ```js 166 | const totalMinutes = 70; 167 | 168 | const hours = Math.floor(totalMinutes / 60); 169 | const minutes = totalMinutes % 60; 170 | console.log(hours); 171 | console.log(minutes); 172 | 173 | const doubleDigitHours = String(hours).padStart(2, 0); 174 | const doubleDigitMinutes = String(minutes).padStart(2, 0); 175 | console.log(`${doubleDigitHours}:${doubleDigitMinutes}`); 176 | ``` 177 | -------------------------------------------------------------------------------- /lesson-01/uk.md: -------------------------------------------------------------------------------- 1 | # Модуль 1. Заняття 1. Змінні, типи та оператори 2 | 3 | ## Example 1 - Математичні оператори 4 | 5 | Виведи на екран загальну кількість яблук та винограду. Різницю яблук та винограду. 6 | 7 | ```js 8 | const apples = 47; 9 | const grapes = 135; 10 | const total = ; 11 | console.log(total) 12 | const diff = ; 13 | console.log(diff) 14 | ``` 15 | 16 | ## Example 2 - Комбіновані оператори 17 | 18 | Заміни вираз перевизначення комбінованим оператором `+=`. 19 | 20 | ```js 21 | let students = 100; 22 | students = students + 50; 23 | console.log(students); 24 | ``` 25 | 26 | ## Example 3 - Пріоритет операторів 27 | 28 | Розбери пріоритет операторів в інструкції привласнення значення змінної 29 | `result`. 30 | 31 | ```js 32 | const result = 108 + 223 - 2 * 5; 33 | console.log(result); 34 | ``` 35 | 36 | ## Example 4 - Клас Math 37 | 38 | Напиши скрипт, який виводить у консоль заокруглені вгору/вниз і т.д. значення 39 | змінної `value`. Використовуй методи `Math.floor()`, `Math.ceil()` та 40 | `Math.round()`. Перевір що буде в консолі при значеннях `27.3` та `27.9`. 41 | 42 | ```js 43 | const value = 27.5; 44 | ``` 45 | 46 | ## Example 5 - Шаблонні рядки 47 | 48 | Склади фразу за допомогою шаблонних рядків `A has B bots in stock`, де A, B - 49 | змінні вставлені в рядок. 50 | 51 | ```js 52 | const companyName = 'Cyberdyne Systems'; 53 | const repairBots = 150; 54 | const defenceBots = 50; 55 | const message = ``; 56 | console.log(message); // "Cyberdyne Systems has 200 bots in stock" 57 | ``` 58 | 59 | ## Example 6 - Методи рядків та чейнінг 60 | 61 | Напиши скрипт, який розраховує індекс маси тіла людини. Для цього 62 | необхідно розділити вагу в кілограмах на квадрат висоти людини у метрах. 63 | 64 | Вага та висота зберігаються у змінних `weight` та `height`, але не як числа, а в 65 | вигляді рядків (спеціально для завдання). Не цілі числа можуть бути задані у вигляді 66 | `24.7` або `24,7`, тобто як роздільник дробової частини може бути 67 | кома. 68 | 69 | Індекс маси тіла необхідно округлити до однієї цифри після коми; 70 | 71 | ```js 72 | let weight = '88,3'; 73 | let height = '1.75'; 74 | 75 | const bmi = ; 76 | console.log(bmi); // 28.8 77 | ``` 78 | 79 | ## Example 7 - Оператори порівняння та приведення типів 80 | 81 | Яким буде результат виразів? 82 | 83 | ```js 84 | console.log(5 > 4); 85 | 86 | console.log(10 >= '7'); 87 | 88 | console.log('2' > '12'); 89 | 90 | console.log('2' < '12'); 91 | 92 | console.log('4' == 4); 93 | 94 | console.log('6' === 6); 95 | 96 | console.log('false' === false); 97 | 98 | console.log(1 == true); 99 | 100 | console.log(1 === true); 101 | 102 | console.log('0' == false); 103 | 104 | console.log('0' === false); 105 | 106 | console.log('Papaya' < 'papaya'); 107 | 108 | console.log('Papaya' === 'papaya'); 109 | 110 | console.log(undefined == null); 111 | 112 | console.log(undefined === null); 113 | ``` 114 | 115 | ## Example 8 - Логічні оператори 116 | 117 | Яким буде результат виразів? 118 | 119 | ```js 120 | console.log(true && 3); 121 | 122 | console.log(false && 3); 123 | 124 | console.log(true && 4 && 'kiwi'); 125 | 126 | console.log(true && 0 && 'kiwi'); 127 | 128 | console.log(true || 3); 129 | 130 | console.log(true || 3 || 4); 131 | 132 | console.log(true || false || 7); 133 | 134 | console.log(null || 2 || undefined); 135 | 136 | console.log((1 && null && 2) > 0); 137 | 138 | console.log(null || (2 && 3) || 4); 139 | ``` 140 | 141 | ## Example 9 - Значення за замовчуванням та оператор нульового злиття 142 | 143 | Отрефактори код так, щоб у змінну `value` присвоювалося значення 144 | змінної `incomingValue`, якщо воно не рівне `undefined` або `null`. В 145 | іншому випадку має присвоюватися значення `defaultValue`. Перевір роботу 146 | скрипта для наступних значень змінної `incomingValue`: null, undefined, 0, 147 | false. Використовуй оператор `??` (nullish coalescing operator). 148 | 149 | ```js 150 | const incomingValue = 5; 151 | const defaultValue = 10; 152 | const value = incomingValue || defaultValue; 153 | console.log(value); 154 | ``` 155 | 156 | ## Example 10 - Оператор % та методи рядків 157 | 158 | Напиши скрипт, який переведе значення `totalMinutes` (кількість хвилин) в 159 | рядок у форматі годин та хвилин `HH:MM`. 160 | 161 | - 70 покаже 01:10 162 | - 450 покаже 07:30 163 | - 1441 покаже 24:01 164 | 165 | ```js 166 | const totalMinutes = 70; 167 | 168 | const hours = Math.floor(totalMinutes / 60); 169 | const minutes = totalMinutes % 60; 170 | console.log(hours); 171 | console.log(minutes); 172 | 173 | const doubleDigitHours = String(hours).padStart(2, 0); 174 | const doubleDigitMinutes = String(minutes).padStart(2, 0); 175 | console.log(`${doubleDigitHours}:${doubleDigitMinutes}`); 176 | ``` 177 | -------------------------------------------------------------------------------- /lesson-02/en.md: -------------------------------------------------------------------------------- 1 | # Module 1. Lesson 2. Branching. Cycles 2 | 3 | ## Example 1 - User Input and Branching 4 | 5 | Using the if..else and prompt constructs, write code that will ask: 6 | `"What is the official name of JavaScript?"`. If the user enters 7 | `ECMAScript`, then show an alert with the string `"Correct!"`, otherwise - 8 | `"Do not know? ECMAScript!"` 9 | 10 | ## Example 2 - Time display (if...else) 11 | 12 | Write a script to display hours and minutes in the browser console as a string 13 | format `"14 hours 26 minutes."`. If the value of the `minutes` variable is `0`, then 14 | output the string `"14 o'clock"`, without minutes. 15 | 16 | ```js 17 | const hours = 14; 18 | const minutes = 26; 19 | let timestring; 20 | 21 | if (minutes > 0) { 22 | timestring = `${hours} ч. ${minutes} min.`; 23 | } else { 24 | timestring = `${hours} h.`; 25 | } 26 | console.log(timestring); 27 | ``` 28 | 29 | ## Example 3 - Branching 30 | 31 | Write a script that prints the string `"This is a positive number"` to the console, 32 | if the user entered a number greater than zero in the prompt. If zero was entered, output 33 | to the console the string `"This is zero"`. If a negative number is passed, in the console 34 | should be the string `"This is a negative number"`. 35 | 36 | ```js 37 | const userInput = prompt('Enter the number'); 38 | ``` 39 | 40 | ## Example 4 - Nested branches 41 | 42 | Write a script that compares the numbers in variables `a` and `b`. If both 43 | values greater than `100`, then print the maximum of them to the console. Otherwise, 44 | the console should show the sum of the value `b` and the number 512. 45 | 46 | ```js 47 | const a = 120; 48 | const b = 180; 49 | ``` 50 | 51 | ## Example 5 - Link Formatting (endsWith) 52 | 53 | Write a script that checks if the value of the `link` variable ends 54 | symbol `/`. if not, add this character to the end of the `link` value. Use 55 | `if...else` construction. 56 | 57 | ```js 58 | let link = 'https://my-site.com/about'; 59 | // Write code below this line 60 | 61 | // Write code above this line 62 | console.log(link); 63 | ``` 64 | 65 | ## Example 6 - Link formatting (includes and logical "AND") 66 | 67 | Write a script that checks if the value of the `link` variable ends by 68 | symbol `/`. If not, append this character to the end of the `link` value, but only 69 | if `link` contains the substring `"my-site"`. Use construction 70 | `if...else`. 71 | 72 | ```js 73 | let link = 'https://somesite.com/about'; 74 | // Write code below this line 75 | 76 | // Write code above this line 77 | console.log(link); 78 | ``` 79 | 80 | ## Example 7 - Link formatting (ternary operator) 81 | 82 | Make code refactoring of the task number 4 code using ternary operator. 83 | 84 | ```js 85 | let link = 'https://somesite.com/about'; 86 | if (link.includes('my-site') && !link.endsWith('/')) { 87 | link += '/'; 88 | } 89 | console.log(link); 90 | ``` 91 | 92 | ## Example 8 - if...else and logical operators 93 | 94 | Write a script that will output a string to the browser console depending on 95 | `hours` variable values. 96 | 97 | If the value of the variable `hours`: 98 | 99 | - less than `17`, output the string `"Pending"` 100 | - greater than or equal to `17` and less than or equal to 24, output the string `"Expires"` 101 | - greater than `24` , output the string `"Overdue"` 102 | 103 | ```js 104 | const hours = 10; 105 | ``` 106 | 107 | ## Example 9 - Project submission deadline (if...else) 108 | 109 | Write a script to display the project deadline time. Use 110 | `if...else` construction. 111 | 112 | - If there are 0 days before the deadline - output the string `"Today"` 113 | - If it's 1 day before the deadline - output the string `"Tomorrow"` 114 | - If it's 2 days before the deadline - output the string `"The day after tomorrow"` 115 | - If it's 3+ days before the deadline - print the string `"Date in the future"` 116 | 117 | ```js 118 | const daysUntilDeadline = 5; 119 | // Write code below this line 120 | ``` 121 | 122 | ## Example 10 - Project submission deadline (switch) 123 | 124 | Make the code refactor of the task number 5 code using `switch`. 125 | 126 | ```js 127 | const daysUntilDeadline = 5; 128 | 129 | if (daysUntilDeadline === 0) { 130 | console.log('Today'); 131 | } else if (daysUntilDeadline === 1) { 132 | console.log('Tomorrow'); 133 | } else if (daysUntilDeadline === 2) { 134 | console.log('The day after tomorrow'); 135 | } else { 136 | console.log('Date in the future'); 137 | } 138 | ``` 139 | 140 | ## Example 11 - The for loop 141 | 142 | Write a for loop that prints numbers in ascending order to the browser console from `min` 143 | to `max`, but only if the number is a multiple of `5`. 144 | 145 | ```js 146 | const max = 100; 147 | const min = 20; 148 | ``` 149 | 150 | ## Example 12 - User Input and Branching 151 | 152 | Write a script that will ask for login using `prompt` and log 153 | result in browser console. 154 | 155 | - If the visitor enters `"Admin"`, then `prompt` prompts for a password 156 | - If nothing is entered or the Esc key is pressed - print the line `"Canceled"` 157 | - Otherwise print the string `"I don't know you"` 158 | 159 | Check password like this: 160 | 161 | - If the password is `"I'm an admin"`, then output the string `"Hello!"` 162 | - Else output the string `"Wrong password"` 163 | -------------------------------------------------------------------------------- /lesson-02/es.md: -------------------------------------------------------------------------------- 1 | # Módulo 1. Clase 2. Oraciones condicionales. Bucles 2 | 3 | ## Ejemplo 1 - Entrada del usuario y oración condicional 4 | 5 | Utilizando la construcción if..else y prompt, escribe un código que pregunte: 6 | `¿Cuál es el nombre oficial de JavaScript?` Si el usuario introduce `ECMAScript`, 7 | entonces muestra una alerta con la cadena `"¡Correcto!"`, en caso contrario, 8 | `"¿No lo sabes? ECMAScript"`. 9 | 10 | ## Ejemplo 2 - Visualización de la hora (if...else) 11 | 12 | Escribe un script para mostrar las horas y los minutos en la consola del navegador 13 | como una cadena con el formato `"14 h. 26 min"`. Si el valor de la variable `minutes` es `0`, entonces 14 | muestra la cadena `"14 h"`, sin minutos. 15 | 16 | ```js 17 | const hours = 14; 18 | const minutes = 26; 19 | let timestring; 20 | 21 | if (minutes > 0) { 22 | timestring = `${hours} h. ${minutes} min.`; 23 | } else { 24 | timestring = `${hours} h.`; 25 | } 26 | console.log(timestring); 27 | ``` 28 | 29 | ## Ejemplo 3 - Oración condicional 30 | 31 | Escriba un script que muestre en la consola la cadena `"Este es un número positivo"`, si el 32 | usuario ha introducido un número mayor que cero en el prompt. Si se ha introducido un cero, 33 | la respuesta en la consola es la cadena `"Esto es cero"`.Si se introduce un número negativo, 34 | en la consola debe aparecer la cadena `"Este es un número negativo"`. 35 | 36 | ```js 37 | const userInput = prompt('Introduzca un número'); 38 | ``` 39 | 40 | ## Ejemplo 4 - Oraciones condicionales encadenadas 41 | 42 | Escribe un script que compare los números de las variables `a` y `b`. Si ambos son mayores 43 | que `100`, imprime el mayor de ellos en la consola. En caso contrario, la consola debería 44 | mostrar la suma del valor de `b` y el número 512. 45 | 46 | ```js 47 | const a = 120; 48 | const b = 180; 49 | ``` 50 | 51 | ## Ejemplo 5 - Formato del link (endsWith) 52 | 53 | Escriba un script que compruebe si el valor de la variable `link` termina con con `/`. Si no es 54 | así, añada dicho símbolo al final del valor de `link`. Utilice la construcción `if...else`. 55 | 56 | ```js 57 | let link = 'https://my-site.com/about'; 58 | // Escriba el código debajo de esta línea 59 | 60 | // Escriba el código arriba de esta línea 61 | console.log(link); 62 | ``` 63 | 64 | ## Ejemplo 6 - Formato del link (includes y lógica «Y») 65 | 66 | Escriba un script que compruebe si el valor de la variable `link` termina con con `/`. 67 | Si no es así, añada dicho símbolo al final del valor de `link`, pero sólo si en `link` hay 68 | una subcadena `"my-site"`. Utilice la construcción `if...else`. 69 | 70 | ```js 71 | let link = 'https://somesite.com/about'; 72 | // Escriba el código debajo de esta línea 73 | 74 | // Escriba el código arriba de esta línea 75 | console.log(link); 76 | ``` 77 | 78 | ## Ejemplo 7 - Formato del link (operador ternario) 79 | 80 | Refactoriza la tarea número 4 utilizando el operador ternario. 81 | 82 | ```js 83 | let link = 'https://somesite.com/about'; 84 | if (link.includes('my-site') && !link.endsWith('/')) { 85 | link += '/'; 86 | } 87 | console.log(link); 88 | ``` 89 | 90 | ## Ejemplo 8 - if...else y operadores lógicos 91 | 92 | Escriba un script que envíe una cadena a la consola del navegador según el 93 | valor de la variable `hours`. 94 | 95 | Si el valor de la variable `hours` es: 96 | 97 | - menor que `17`, muestra la cadena `"Pending"` 98 | - mayor o igual que `17` y menor o igual que 24, muestra la cadena `"Expires"` 99 | - mayor que `24` , muestra la cadena `"Overdue"` 100 | 101 | ```js 102 | const hours = 10; 103 | ``` 104 | 105 | ## Ejemplo 9 - Plazo de entrega del proyecto (if...else) 106 | 107 | Escriba un script para mostrar la hora de la fecha límite para entregar un proyecto. 108 | Utilice la construcción `if...else`. 109 | 110 | - Si faltan 0 días - muestra la cadena `"Hoy"` 111 | - Si falta 1 día - muestra la cadena `"Mañana"` 112 | - Si faltan 2 días - muestra la cadena `"Pasado mañana"` 113 | - Si faltan 3+ días - muestra la cadena `"La fecha en el futuro"` 114 | 115 | ```js 116 | const daysUntilDeadline = 5; 117 | // Escriba el código debajo de esta línea 118 | ``` 119 | 120 | ## Ejemplo 10 - Plazo de entrega del proyecto (switch) 121 | 122 | Refactoriza el código de la tarea número 5 utilizando `switch`. 123 | 124 | ```js 125 | const daysUntilDeadline = 5; 126 | 127 | if (daysUntilDeadline === 0) { 128 | console.log('Hoy'); 129 | } else if (daysUntilDeadline === 1) { 130 | console.log('Mañana'); 131 | } else if (daysUntilDeadline === 2) { 132 | console.log('Pasado mañana'); 133 | } else { 134 | console.log('Fecha en el futuro'); 135 | } 136 | ``` 137 | 138 | ## Ejemplo 11 - Bucle for 139 | 140 | Escriba un bucle for que muestre los números en orden ascendente de `min` a `max` en 141 | la consola del navegador, pero sólo si el número es un múltiplo de `5`. 142 | 143 | ```js 144 | const max = 100; 145 | const min = 20; 146 | ``` 147 | 148 | ## Ejemplo 12 - Entrada del usuario y oración condicional 149 | 150 | Escribe un script que pida un login usando `prompt` y haga un log del resultado en la consola del navegador. 151 | 152 | - Si el visitante introduce `Admin`, `prompt` le pide una contraseña 153 | - Si no se introduce nada y pulsa la tecla Esc - muestra la cadena `"Cancelado"` 154 | - En caso contrario, muestra la cadena `"No te conozco"` 155 | 156 | Comprobar la contraseña de la siguiente manera: 157 | 158 | - Si se introduce la contraseña `"Soy el admin"`, mostrar la cadena `"¡Hola!"` 159 | - En caso contrario, mostrar la cadena `"Contraseña incorrecta"` 160 | -------------------------------------------------------------------------------- /lesson-02/ru.md: -------------------------------------------------------------------------------- 1 | # Модуль 1. Занятие 2. Ветвления. Циклы 2 | 3 | ## Example 1 - Ввод пользователя и ветвления 4 | 5 | Используя конструкцию if..else и prompt, напиши код, который будет спрашивать: 6 | `"Какое официальное название JavaScript?"`. Если пользователь вводит 7 | `ECMAScript`, то показывай alert со строкой `"Верно!"`, в противном случае - 8 | `"Не знаете? ECMAScript!"` 9 | 10 | ## Example 2 - Отображение времени (if...else) 11 | 12 | Напиши скрипт для отображения часов и минут в консоли браузера в виде строки 13 | формата `"14 ч. 26 мин."`. Если значение переменной `minutes` равно `0`, то 14 | выводи строку `"14 ч."`, без минут. 15 | 16 | ```js 17 | const hours = 14; 18 | const minutes = 26; 19 | let timestring; 20 | 21 | if (minutes > 0) { 22 | timestring = `${hours} ч. ${minutes} мин.`; 23 | } else { 24 | timestring = `${hours} ч.`; 25 | } 26 | console.log(timestring); 27 | ``` 28 | 29 | ## Example 3 - Ветвеления 30 | 31 | Напиши скрипт, который выводит в консоль строку `"Это положительное число"`, 32 | если в prompt пользователь ввел число больше нуля. Если был введен ноль, выводи 33 | в консоль строку `"Это ноль"`. Если передали отрицательное число, в консоли 34 | должна быть строка `"Это отрицательное число"`. 35 | 36 | ```js 37 | const userInput = prompt('Введите число'); 38 | ``` 39 | 40 | ## Example 4 - Вложенные ветвления 41 | 42 | Напиши скрипт, который сравнивает числа в переменных `a` и `b`. Если оба 43 | значения больше `100`, то выведи в консоль максимальное из них. В противном 44 | случае в консоли должна быть сумма значения `b` и числа 512. 45 | 46 | ```js 47 | const a = 120; 48 | const b = 180; 49 | ``` 50 | 51 | ## Example 5 - Форматирование ссылки (endsWith) 52 | 53 | Напиши скрипт который проверяет заканчивается ли значение переменной `link` 54 | символом `/`. Если нет, добавь в конец значения `link` этот символ. Используй 55 | конструкцию `if...else`. 56 | 57 | ```js 58 | let link = 'https://my-site.com/about'; 59 | // Пиши код ниже этой строки 60 | 61 | // Пиши код выше этой строки 62 | console.log(link); 63 | ``` 64 | 65 | ## Example 6 - Форматирование ссылки (includes и логическое «И») 66 | 67 | Напиши скрипт который проверяет заканчивается ли значение переменной `link` 68 | символом `/`. Если нет, добавь в конец значения `link` этот символ, но только в 69 | том случае, если в `link` есть подстрока `"my-site"`. Используй конструкцию 70 | `if...else`. 71 | 72 | ```js 73 | let link = 'https://somesite.com/about'; 74 | // Пиши код ниже этой строки 75 | 76 | // Пиши код выше этой строки 77 | console.log(link); 78 | ``` 79 | 80 | ## Example 7 - Форматирование ссылки (тернарный оператор) 81 | 82 | Выполни рефакторинг кода задачи номер 4 используя тернарный оператор. 83 | 84 | ```js 85 | let link = 'https://somesite.com/about'; 86 | if (link.includes('my-site') && !link.endsWith('/')) { 87 | link += '/'; 88 | } 89 | console.log(link); 90 | ``` 91 | 92 | ## Example 8 - if...else и логические операторы 93 | 94 | Напиши скрипт который будет выводить в консоль браузера строку в зависимости от 95 | значения переменной `hours`. 96 | 97 | Если значение переменной `hours`: 98 | 99 | - меньше `17`, выводи строку `"Pending"` 100 | - больше либо равно `17` и меньше либо равно 24, выводи строку `"Expires"` 101 | - больше `24` , выводи строку `"Overdue"` 102 | 103 | ```js 104 | const hours = 10; 105 | ``` 106 | 107 | ## Example 9 - Дедлайн сдачи проекта (if...else) 108 | 109 | Напиши скрипт для отображения времени дедлайна сдачи проекта. Используй 110 | конструкцию `if...else`. 111 | 112 | - Eсли до дедлайна 0 дней - выведи строку `"Сегодня"` 113 | - Eсли до дедлайна 1 день - выведи строку `"Завтра"` 114 | - Eсли до дедлайна 2 дня - выведи строку `"Послезавтра"` 115 | - Eсли до дедлайна 3+ дней - выведи строку `"Дата в будущем"` 116 | 117 | ```js 118 | const daysUntilDeadline = 5; 119 | // Пиши код ниже этой строки 120 | ``` 121 | 122 | ## Example 10 - Дедлайн сдачи проекта (switch) 123 | 124 | Выполни рефакторинг кода задачи номер 5 используя `switch`. 125 | 126 | ```js 127 | const daysUntilDeadline = 5; 128 | 129 | if (daysUntilDeadline === 0) { 130 | console.log('Сегодня'); 131 | } else if (daysUntilDeadline === 1) { 132 | console.log('Завтра'); 133 | } else if (daysUntilDeadline === 2) { 134 | console.log('Послезавтра'); 135 | } else { 136 | console.log('Дата в будущем'); 137 | } 138 | ``` 139 | 140 | ## Example 11 - Цикл for 141 | 142 | Напиши цикл for который выводит в консоль браузера числа по возрастанию от `min` 143 | до `max`, но только если число кратное `5`. 144 | 145 | ```js 146 | const max = 100; 147 | const min = 20; 148 | ``` 149 | 150 | ## Example 12 - Ввод пользователя и ветвления 151 | 152 | Напиши скрипт, который будет спрашивать логин с помощью `prompt` и логировать 153 | результат в консоль браузера. 154 | 155 | - Если посетитель вводит `"Админ"`, то `prompt` запрашивает пароль 156 | - Если ничего не введено или нажата клавиша Esc - вывести строку `"Отменено"` 157 | - В противном случае вывести строку `"Я вас не знаю"` 158 | 159 | Пароль проверять так: 160 | 161 | - Если введён пароль `"Я админ"`, то вывести строку `"Здравствуйте!"` 162 | - Иначе выводить строку `"Неверный пароль"` 163 | -------------------------------------------------------------------------------- /lesson-02/uk.md: -------------------------------------------------------------------------------- 1 | # Модуль 1. Заняття 2. Розгалуження. Цикли 2 | 3 | ## Example 1 - Введення користувача та розгалуження 4 | 5 | Використовуючи конструкцію if..else та prompt, напиши код, який питатиме: 6 | `"Яка офіційна назва JavaScript?"`. Якщо користувач вводить 7 | `ECMAScript`, то показуй alert з рядком `"Правильно!"`, в іншому випадку - 8 | `"Не знаєте? ECMAScript!"` 9 | 10 | ## Example 2 - Відображення часу (if...else) 11 | 12 | Напиши скрипт для відображення годин та хвилин у консолі браузера у вигляді рядка 13 | формату `"14 г. 26 хв."`. Якщо значення змінної `minutes` дорівнює `0`, то 14 | виводь рядок `"14 г."`, без хвилин. 15 | 16 | ```js 17 | const hours = 14; 18 | const minutes = 26; 19 | let timestring; 20 | 21 | if (minutes > 0) { 22 | timestring = `${hours} г. ${minutes} хв.`; 23 | } else { 24 | timestring = `${hours} г.`; 25 | } 26 | console.log(timestring); 27 | ``` 28 | 29 | ## Example 3 - Розгалуження 30 | 31 | Напиши скрипт, який виводить у консоль рядок `"Це позитивне число"`, 32 | якщо у prompt користувач ввів число більше нуля. Якщо було введено нуль, виводь 33 | в консоль рядок `"Це нуль"`. Якщо передали від'ємне число, у консолі 34 | повинен бути рядок `"Це негативне число"`. 35 | 36 | ```js 37 | const userInput = prompt('Введіть число'); 38 | ``` 39 | 40 | ## Example 4 - Вкладені розгалуження 41 | 42 | Напиши скрипт, який порівнює числа у змінних `a` та `b`. Якщо обидва 43 | значення більше `100`, то виведи в консоль максимальне з них. В протилежному 44 | випадку у консолі повинна бути сума значення `b` та числа 512. 45 | 46 | ```js 47 | const a = 120; 48 | const b = 180; 49 | ``` 50 | 51 | ## Example 5 - Форматування посилання (endsWith) 52 | 53 | Напиши скрипт який перевіряє чи закінчується значення змінної `link` 54 | символом `/`. Якщо ні, додай до кінця значення `link` цей символ. Використовуй 55 | конструкцію `if...else`. 56 | 57 | ```js 58 | let link = 'https://my-site.com/about'; 59 | // Пиши код нижче за цей рядок 60 | 61 | // Пиши код вище за цей рядок 62 | console.log(link); 63 | ``` 64 | 65 | ## Example 6 - Форматування посилання (includes та логічне «І») 66 | 67 | Напиши скрипт який перевіряє чи закінчується значення змінної `link` 68 | символом `/`. Якщо ні, додай до кінця значення `link` цей символ, але тільки в 69 | тому випадку, якщо в `link` є підрядок `"my-site"`. Використовуй конструкцію 70 | `if...else`. 71 | 72 | ```js 73 | let link = 'https://somesite.com/about'; 74 | // Пиши код нижче за цей рядок 75 | 76 | // Пиши код вище за цей рядок 77 | console.log(link); 78 | ``` 79 | 80 | ## Example 7 - Форматування посилання (тернарний оператор) 81 | 82 | Виконай рефакторинг коду задачі номер 4, використовуючи тернарний оператор. 83 | 84 | ```js 85 | let link = 'https://somesite.com/about'; 86 | if (link.includes('my-site') && !link.endsWith('/')) { 87 | link += '/'; 88 | } 89 | console.log(link); 90 | ``` 91 | 92 | ## Example 8 - if...else та логічні оператори 93 | 94 | Напиши скрипт який виводитиме в консоль браузера рядок залежно від 95 | значення змінної `hours`. 96 | 97 | Якщо значення змінної `hours`: 98 | 99 | - менше `17`, виводь рядок `"Pending"` 100 | - більше або дорівнює `17` і менше або дорівнює 24, виводь рядок `"Expires"` 101 | - більше `24` , виводь рядок `"Overdue"` 102 | 103 | ```js 104 | const hours = 10; 105 | ``` 106 | 107 | ## Example 9 - Дедлайн здачі проекту (if...else) 108 | 109 | Напиши скрипт для відображення часу дедлайну здачі проекту. Використовуй 110 | конструкцію `if...else`. 111 | 112 | - Якщо до дедлайну 0 днів - виведи рядок `"Сьогодні"` 113 | - Якщо до дедлайну 1 день - виведи рядок `"Завтра"` 114 | - Якщо до дедлайну 2 дні - виведи рядок `"Післязавтра"` 115 | - Якщо до дедлайну 3+ днів - виведи рядок `"Дата у майбутньому"` 116 | 117 | ```js 118 | const daysUntilDeadline = 5; 119 | // Пиши код нижче за цей рядок 120 | ``` 121 | 122 | ## Example 10 - Дедлайн здачі проекту (switch) 123 | 124 | Виконай рефакторинг коду задачі номер 5 використовуючи `switch`. 125 | 126 | ```js 127 | const daysUntilDeadline = 5; 128 | 129 | if (daysUntilDeadline === 0) { 130 | console.log('Сьогодні'); 131 | } else if (daysUntilDeadline === 1) { 132 | console.log('Завтра'); 133 | } else if (daysUntilDeadline === 2) { 134 | console.log('Післязавтра'); 135 | } else { 136 | console.log('Дата у майбутньому'); 137 | } 138 | ``` 139 | 140 | ## Example 11 - Цикл for 141 | 142 | Напиши цикл for, який виводить у консоль браузера числа за зростанням від `min` 143 | до `max`, але тільки якщо число кратне `5`. 144 | 145 | ```js 146 | const max = 100; 147 | const min = 20; 148 | ``` 149 | 150 | ## Example 12 - Введення користувача та розгалуження 151 | 152 | Напиши скрипт, який питатиме логін за допомогою `prompt` та логувати 153 | результат у консоль браузера. 154 | 155 | - Якщо відвідувач вводить `"Адмін"`, то `prompt` запитує пароль 156 | - Якщо нічого не введено або натиснуто клавішу Esc - вивести рядок `"Скасовано"` 157 | - В іншому випадку вивести рядок `"Я вас не знаю"` 158 | 159 | Пароль перевіряти так: 160 | 161 | - Якщо введено пароль `"Я адмін"`, то вивести рядок `"Здрастуйте!"` 162 | - Інакше виводити рядок `"Невірний пароль"` 163 | -------------------------------------------------------------------------------- /lesson-03/en.md: -------------------------------------------------------------------------------- 1 | # Module 2 - Lesson 3 - Arrays 2 | 3 | ## Example 1 - Basic operations with an array 4 | 5 | 1. Create an array `genres` with elements "Jazz" and "Blues". 6 | 2. Add "Rock and Roll" to the end. 7 | 3. Print the first element of the array to the console. 8 | 4. Print the last element of the array to the console. The code should work for an array 9 | random length. 10 | 5. Remove the first element and print it to the console. 11 | 6. Insert "Country" and "Reggae" at the beginning of the array. 12 | 13 | ```js 14 | const genres = ; 15 | ``` 16 | 17 | ## Example 2 - Arrays and Strings 18 | 19 | Write a script to calculate the area of a rectangle with sides, whichvalues 20 | values are stored in the `values` variable as a string. Values guaranteed 21 | separated by a space. 22 | 23 | ```js 24 | const values = '8 11'; 25 | ``` 26 | 27 | ## Example 3 - Array iteration 28 | 29 | Write a script to iterate over the `fruits` array with a `for` loop. For each array element 30 | print a string in the format `element_number: element_value` to the console. 31 | Element numbering must start from `1`. 32 | 33 | ```js 34 | const fruits = ['🍎', '🍇', '🍑', '🍌', '🍋']; 35 | ``` 36 | 37 | ## Example 4 -Arrays and Loops 38 | 39 | Write a script that prints the user's name and phone number to the console. 40 | The `names` and `phones` variables store strings of names and phone numbers, 41 | separated by commas. The sequence number of names and phone numbers in the lines indicates a match. 42 | The number of names and phone numbers is guaranteed to be the same. 43 | 44 | ```js 45 | const names = 'Jacob,William,Solomon,Artemis'; 46 | const phones = '89001234567,89001112233,890055566377,890055566300'; 47 | ``` 48 | 49 | ## Example 5 - Arrays and Strings 50 | 51 | Write a script that prints to the console all the words of a string except the first and 52 | the last one. The resulting string must not start or end 53 | whitespace character. The script should work for any line. 54 | 55 | ```js 56 | const string = 'Welcome to the future'; 57 | ``` 58 | 59 | ## Example 6 - Arrays and Strings 60 | 61 | Write a script that "unwraps" a string (reverse letter order) and prints 62 | it to the console. 63 | 64 | ```js 65 | const string = 'Welcome to the future'; 66 | ``` 67 | 68 | ## Example 7 - Sorting an array with a loop 69 | 70 | Write a script to sort an array of strings alphabetically by the first letter 71 | of an element. 72 | 73 | ```js 74 | const langs = ['python', 'javascript', 'c++', 'haskel', 'php', 'ruby']; 75 | ``` 76 | 77 | ## Example 8 - Search for an element 78 | 79 | Write a script to find the smallest number in an array. The code should work 80 | for any array of numbers. Use a loop to solve problems. 81 | 82 | ```js 83 | const numbers = [2, 17, 94, 1, 23, 37]; 84 | let min; 85 | console.log(min); // 1 86 | ``` 87 | -------------------------------------------------------------------------------- /lesson-03/es.md: -------------------------------------------------------------------------------- 1 | # Módulo 2. Clase 3. Arrays 2 | 3 | ## Ejemplo 1 - Operaciones básicas con un array 4 | 5 | 1. Crea un Array `genres` con lo elementos «Jazz» y «Blues». 6 | 2. Agrega «Rock n Roll» al final. 7 | 3. Muestra el primer elemento del Array en la consola. 8 | 4. Muestra el último elemento del Array en la consola. El código 9 | debería funcionar para un array de cualquier longitud. 10 | 5. Elimina el primer elemento y muestralo en la consola. 11 | 6. Inserta "Country" y "Reggae" al principio del Array. 12 | 13 | ```js 14 | const genres = ; 15 | ``` 16 | 17 | ## Ejemplo 2 - Arrays y Cadenas 18 | 19 | Escribe un script para calcular el área de un rectángulo con lados cuyos 20 | valores se almacenan en la variable `values` en forma de cadena. 21 | Se garantiza que los valores están separados por un espacio. 22 | 23 | ```js 24 | const values = '8 11'; 25 | ``` 26 | 27 | ## Ejemplo 3 - Indexación de un Array 28 | 29 | Escribe un script para buscar en el array `fruits` con un bucle `for`. Para cada 30 | elemento del Array, envía a la consola una cadena con el formato `número_de_elemento: valor_de_elemento`. 31 | La numeración de los elementos debe empezar por `1`. 32 | 33 | ```js 34 | const fruits = ['🍎', '🍇', '🍑', '🍌', '🍋']; 35 | ``` 36 | 37 | ## Ejemplo 4 - Arrays y bucles 38 | 39 | Escriba un script que muestre el nombre y el número de teléfono del usuario en la consola. 40 | En las variables `names` y `phones` se almacenan cadenas de nombres y números de teléfono, separados 41 | por comas. El índice de los nombres y números de teléfono en las líneas indica correspondencia. 42 | La cantidad de nombres y teléfonos debe de ser igual. 43 | 44 | ```js 45 | const names = 'Jacob,William,Solomon,Artemis'; 46 | const phones = '89001234567,89001112233,890055566377,890055566300'; 47 | ``` 48 | 49 | ## Ejemplo 5 - Arrays y cadenas 50 | 51 | Escriba un script que muestre en la consola todas las palabras de la cadena 52 | excepto la primera y la última. La cadena resultante no debe comenzar ni terminar 53 | con un espacio en blanco. El script debería funcionar para cualquier cadena. 54 | 55 | ```js 56 | const string = 'Welcome to the future'; 57 | ``` 58 | 59 | ## Ejemplo 6 - Arrays y cadenas 60 | 61 | Escriba un script que "invierta" la cadena (invierta el orden de las letras) 62 | y la muestre en la consola. 63 | 64 | ```js 65 | const string = 'Welcome to the future'; 66 | ``` 67 | 68 | ## Ejemplo 7 - Ordenar Arrays con un bucle 69 | 70 | Escribe un script para ordenar un array de cadenas en orden alfabético 71 | según la primera letra elemento. 72 | 73 | ```js 74 | const langs = ['python', 'javascript', 'c++', 'haskel', 'php', 'ruby']; 75 | ``` 76 | 77 | ## Ejemplo 8 - Buscar un elemento 78 | 79 | Escribe un script para encontrar el número más pequeño en el Array. El código 80 | debería funcionar para cualquier Array de números. Utiliza un bucle para resolver el problema. 81 | 82 | ```js 83 | const numbers = [2, 17, 94, 1, 23, 37]; 84 | let min; 85 | console.log(min); // 1 86 | ``` 87 | -------------------------------------------------------------------------------- /lesson-03/ru.md: -------------------------------------------------------------------------------- 1 | # Модуль 2. Занятие 3. Массивы 2 | 3 | ## Example 1 - Базовые операции с массивом 4 | 5 | 1. Создайте массив `genres` с элементами «Jazz» и «Blues». 6 | 2. Добавьте «Рок-н-ролл» в конец. 7 | 3. Выведите в консоль первый элемент массива. 8 | 4. Выведите в консоль последний элемент массива. Код должен работать для массива 9 | произвольной длины. 10 | 5. Удалите первый элемент и выведите его в консоль. 11 | 6. Вставьте «Country» и «Reggae» в начало массива. 12 | 13 | ```js 14 | const genres = ; 15 | ``` 16 | 17 | ## Example 2 - Массивы и строки 18 | 19 | Напиши скрипт для вычисления площади прямоугольника со сторонами, значения 20 | которых хранятся в переменной `values` в виде строки. Значения гарантированно 21 | разделены пробелом. 22 | 23 | ```js 24 | const values = '8 11'; 25 | ``` 26 | 27 | ## Example 3 - Перебор массива 28 | 29 | Напиши скрипт для перебора массива `fruits` циклом `for`. Для каждого элемента 30 | массива выведи в консоль строку в формате `номер_элемента: значение_элемента`. 31 | Нумерация элементов должна начинаться с `1`. 32 | 33 | ```js 34 | const fruits = ['🍎', '🍇', '🍑', '🍌', '🍋']; 35 | ``` 36 | 37 | ## Example 4 - Массивы и циклы 38 | 39 | Напиши скрипт который выводит в консоль имя и телефонный номер пользователя. В 40 | переменных `names` и `phones` хранятся строки имен и телефонных номеров, 41 | разделенные запятыми. Порядковый номер имен и телефонов в строках указывают на 42 | соответствие. Количество имен и телефонов гарантированно одинаковое. 43 | 44 | ```js 45 | const names = 'Jacob,William,Solomon,Artemis'; 46 | const phones = '89001234567,89001112233,890055566377,890055566300'; 47 | ``` 48 | 49 | ## Example 5 - Массивы и строки 50 | 51 | Напиши скрипт который выводит в консоль все слова строки кроме первого и 52 | последнего. Результирующая строка не должна начинаться или заканчиваться 53 | пробельным символом. Скрипт должен работать для любой строки. 54 | 55 | ```js 56 | const string = 'Welcome to the future'; 57 | ``` 58 | 59 | ## Example 6 - Массивы и строки 60 | 61 | Напиши скрипт который «разворачивает» строку (обратный порядок букв) и выводит 62 | ее в консоль. 63 | 64 | ```js 65 | const string = 'Welcome to the future'; 66 | ``` 67 | 68 | ## Example 7 - Сортировка массива с циклом 69 | 70 | Напиши скрипт сортировки массива строк в алфавитном порядке по первой букве 71 | элемента. 72 | 73 | ```js 74 | const langs = ['python', 'javascript', 'c++', 'haskel', 'php', 'ruby']; 75 | ``` 76 | 77 | ## Example 8 - Поиск элемента 78 | 79 | Напиши скрипт поиска самого маленького числа в массиве. Код должен работать для 80 | любого массива чисел. Используй цикл для решения задачи. 81 | 82 | ```js 83 | const numbers = [2, 17, 94, 1, 23, 37]; 84 | let min; 85 | console.log(min); // 1 86 | ``` 87 | -------------------------------------------------------------------------------- /lesson-03/uk.md: -------------------------------------------------------------------------------- 1 | # Модуль 2. Заняття 3. Масиви 2 | 3 | ## Example 1 - Базові операції з масивом 4 | 5 | 1. Створіть масив `genres` з елементами «Jazz» та «Blues». 6 | 2. Додайте «Рок-н-рол» до кінця. 7 | 3. Виведіть у консоль перший елемент масиву. 8 | 4. Виведіть у консоль останній елемент масиву. Код повинен працювати для масиву 9 | довільної довжини. 10 | 5. Видаліть перший елемент та виведіть його в консоль. 11 | 6. Вставте «Country» та «Reggae» на початок масиву. 12 | 13 | ```js 14 | const genres = ; 15 | ``` 16 | 17 | ## Example 2 - Масиви та рядки 18 | 19 | Напиши скрипт для обчислення площі прямокутника зі сторонами, значення 20 | яких зберігаються у змінній `values` у вигляді рядка. Значення гарантовано 21 | розділені пробілом. 22 | 23 | ```js 24 | const values = '8 11'; 25 | ``` 26 | 27 | ## Example 3 - Перебір масиву 28 | 29 | Напиши скрипт для перебору масиву `fruits` циклом `for`. Для кожного елемента 30 | масиву виведи в консоль рядок у форматі `номер_елемента: значення_елемента`. 31 | Нумерація елементів повинна починатися з `1`. 32 | 33 | ```js 34 | const fruits = ['🍎', '🍇', '🍑', '🍌', '🍋']; 35 | ``` 36 | 37 | ## Example 4 - Масиви та цикли 38 | 39 | Напиши скрипт, який виводить у консоль ім'я та телефонний номер користувача. У 40 | змінних `names` та `phones` зберігаються рядки імен та телефонних номерів, 41 | розділені комами. Порядковий номер імен та телефонів у рядках вказують на 42 | відповідність. Кількість імен та телефонів гарантовано однакова. 43 | 44 | ```js 45 | const names = 'Jacob,William,Solomon,Artemis'; 46 | const phones = '89001234567,89001112233,890055566377,890055566300'; 47 | ``` 48 | 49 | ## Example 5 - Масиви та рядки 50 | 51 | Напиши скрипт, який виводить у консоль усі слова рядка крім першого і 52 | останнього. Результуючий рядок не повинен починатися або закінчуватися 53 | символ пробілу. Скрипт повинен працювати для будь-якого рядка. 54 | 55 | ```js 56 | const string = 'Welcome to the future'; 57 | ``` 58 | 59 | ## Example 6 - Масиви та рядки 60 | 61 | Напиши скрипт, який «розгортає» рядок (зворотний порядок букв) і виводить 62 | його в консоль. 63 | 64 | ```js 65 | const string = 'Welcome to the future'; 66 | ``` 67 | 68 | ## Example 7 - Сортування масиву із циклом 69 | 70 | Напиши скрипт сортування масиву рядків в алфавітному порядку за першою літерою 71 | елемента. 72 | 73 | ```js 74 | const langs = ['python', 'javascript', 'c++', 'haskel', 'php', 'ruby']; 75 | ``` 76 | 77 | ## Example 8 - Пошук елемента 78 | 79 | Напиши скрипт пошуку найменшого числа у масиві. Код повинен працювати для 80 | будь-якого масиву чисел. Використовуй цикл для розв'язання задачі. 81 | 82 | ```js 83 | const numbers = [2, 17, 94, 1, 23, 37]; 84 | let min; 85 | console.log(min); // 1 86 | ``` 87 | -------------------------------------------------------------------------------- /lesson-04/en.md: -------------------------------------------------------------------------------- 1 | # Module 2 - Lesson 4 - Functions 2 | 3 | ## Example 1 - Body mass index 4 | Write a function `calcBMI(weight, height)` that calculates and returns the body mass 5 | index of a person. To do this, divide the weight in kilograms by 6 | square of a person's height in meters. 7 | 8 | The weight and height will be specially passed as strings. Non-integer numbers can be 9 | specified as `24.7` or `24.7`, i.e. a comma can be used 10 | as a decimal separator. 11 | 12 | Body mass index must be rounded to one decimal place; 13 | 14 | ```js 15 | const bmi = calcBMI('88,3', '1.75'); 16 | console.log(bmi); // 28.8 17 | ``` 18 | 19 | ## Example 2 - Smaller of numbers 20 | 21 | Write a function `min(a,b)` that returns the smaller of the numbers `a` and `b`. 22 | 23 | ```js 24 | console.log(min(2, 5)); // 2 25 | console.log(min(3, -1)); // -1 26 | console.log(min(1, 1)); // 1 27 | ``` 28 | 29 | ## Example 3 - Area of a rectangle 30 | 31 | Write a function `getRectArea(dimensions)` to calculate the area of a rectangle 32 | with sides, the values of which will be passed to the `dimensions` parameter as a string. 33 | Values are guaranteed to be separated by a space. 34 | 35 | ```js 36 | function getRectArea(dimensions) {} 37 | 38 | console.log(getRectArea('8 11')); 39 | ``` 40 | 41 | ## Example 4 - Element logging 42 | 43 | Write a function `logItems(items)` that takes an array and uses a `for` loop 44 | that for each element of the array will print a message to the console 45 | in the format ` - `. The numbering 46 | of elements should start with `1`. 47 | 48 | For example, for the first element of the array `['Mango', 'Poly', 'Ajax']` with index `0` 49 | will print `1 - Mango` and for index 2 will print `3 - Ajax`. 50 | 51 | ```js 52 | function logItems(items) {} 53 | 54 | logItems(['Mango', 'Poly', 'Ajax']); 55 | logItems(['🍎', '🍇', '🍑', '🍌', '🍋']); 56 | ``` 57 | 58 | ## Example 5 - Contact logging 59 | 60 | Write a function `printContactsInfo(names, phones)` that prints to the console the name 61 | and the user's phone number. The `names` and `phones` parameters will be passed 62 | strings of names and phone numbers separated by commas. Sequence number of names and 63 | phone numbers in the rows indicate a match. Number of names and phones 64 | guaranteed to be the same. 65 | 66 | ```js 67 | function printContactsInfo(names, phones) {} 68 | 69 | printContactsInfo( 70 | 'Jacob,William,Solomon,Artemis', 71 | '89001234567,89001112233,890055566377,890055566300', 72 | ); 73 | ``` 74 | 75 | ## Example 6 - Finding the largest element 76 | 77 | Write a function `findLargestNumber(numbers)` that looks for the largest number in 78 | array. 79 | 80 | ```js 81 | function findLargestNumber(numbers) {} 82 | 83 | console.log(findLargestNumber([2, 17, 94, 1, 23, 37])); // 94 84 | console.log(findLargestNumber([49, 4, 7, 83, 12])); // 83 85 | ``` 86 | 87 | ## Example 7 - Average value 88 | 89 | Write a `calAverage()` function that takes an arbitrary number of arguments 90 | and returns their average. All arguments will be only numbers. 91 | 92 | ```js 93 | function calAverage() {} 94 | 95 | console.log(calAverage(1, 2, 3, 4)); // 2.5 96 | console.log(calAverage(14, 8, 2)); // 8 97 | console.log(calAverage(27, 43, 2, 8, 36)); // 23.2 98 | ``` 99 | 100 | ## Example 8 - Time Formatting 101 | 102 | Write a function `formatTime(minutes)` that will translate the value of `minutes` 103 | (number of minutes) to a string in hour and minute format `HH:MM`. 104 | 105 | ```js 106 | const hours = Math.floor(totalMinutes / 60); 107 | const minutes = totalMinutes % 60; 108 | console.log(hours); 109 | console.log(minutes); 110 | 111 | const doubleDigitHours = String(hours).padStart(2, 0); 112 | const doubleDigitMinutes = String(minutes).padStart(2, 0); 113 | console.log(`${doubleDigitHours}:${doubleDigitMinutes}`); 114 | 115 | function formatTime(minutes) {} 116 | 117 | console.log(formatTime(70)); // "01:10" 118 | console.log(formatTime(450)); // "07:30" 119 | console.log(formatTime(1441)); // "24:01" 120 | ``` 121 | 122 | ## Example 9 -Collection of courses (includes, indexOf, push, etc.) 123 | 124 | Write functions to work with the `courses` collection of training courses: 125 | 126 | - `addCourse(name)` - adds a course to the end of the collection 127 | - `removeCourse(name)` - removes a course from the collection 128 | - `updateCourse(oldName, newName)` - changes the name to a new one 129 | 130 | ```js 131 | const courses = ['HTML', 'CSS', 'JavaScript', 'React', 'PostgreSQL']; 132 | 133 | addCourse('Express'); 134 | console.log(courses); // ['HTML', 'CSS', 'JavaScript', 'React', 'PostgreSQL', 'Express'] 135 | addCourse('CSS'); // ' You already have this course' 136 | 137 | removeCourse('React'); 138 | console.log(courses); // ['HTML', 'CSS', 'JavaScript', 'PostgreSQL', 'Express'] 139 | removeCourse('Vue'); // 'Course with this name was not found' 140 | 141 | updateCourse('Express', 'NestJS'); 142 | console.log(courses); // ['HTML', 'CSS', 'JavaScript', 'PostgreSQL', 'NestJS'] 143 | ``` 144 | -------------------------------------------------------------------------------- /lesson-04/es.md: -------------------------------------------------------------------------------- 1 | # Módulo 2. Clase 4. Funciones 2 | 3 | ## Ejemplo 1 - Índice de masa corporal 4 | 5 | Escribe una función `calcBMI(weight, height)` que calcule y retorne el índice de masa 6 | corporal de una persona. Para ello, divide el peso en kilogramos por 7 | el cuadrado de la altura de la persona en metros. 8 | 9 | El peso y la altura se podrán seran dados específicamente como cadenas. Las fracciones 10 | se pueden dar de estas maneras `24.7` o `24,7`, es decir, el separador de fracciones 11 | puede ser una coma. 12 | 13 | El índice de masa corporal debe redondearse a un decimal; 14 | 15 | ```js 16 | const bmi = calcBMI('88,3', '1.75'); 17 | console.log(bmi); // 28.8 18 | ``` 19 | 20 | ## Ejemplo 2 - El menor de los números 21 | 22 | Escribe una función `min(a,b)` que devuelva el menor de los números `a` y `b`. 23 | 24 | ```js 25 | console.log(min(2, 5)); // 2 26 | console.log(min(3, -1)); // -1 27 | console.log(min(1, 1)); // 1 28 | ``` 29 | 30 | ## Ejemplo 3 - Área del rectángulo 31 | 32 | Escribe una función `getRectArea(dimensions)` para calcular el área de un rectángulo 33 | con los lados cuyos valores estaran en el parámetro `dimensiones` en forma de cadena. 34 | Asegurate de que los valores estén separados por un espacio. 35 | 36 | ```js 37 | function getRectArea(dimensions) {} 38 | 39 | console.log(getRectArea('8 11')); 40 | ``` 41 | 42 | ## Ejemplo 4 - Registro (log) de elementos 43 | 44 | Escriba una función `logItems(items)` que reciba un Array y utilice un bucle `for` que 45 | para cada elemento del Array, envíe un mensaje a la consola con el formato 46 | ` - `. La numeración de los elementos debe empezar por `1`. 47 | 48 | Por ejemplo, para el primer elemento del array `['Mango', 'Poly', 'Ajax']` con 49 | índice `0` imprimirá `1 - Mango`, y para el índice 2 imprimirá `3 - Ajax`. 50 | 51 | ```js 52 | function logItems(items) {} 53 | 54 | logItems(['Mango', 'Poly', 'Ajax']); 55 | logItems(['🍎', '🍇', '🍑', '🍌', '🍋']); 56 | ``` 57 | 58 | ## Ejemplo 5 - Registro (log) de contactos 59 | 60 | Escriba una función `printContactsInfo(names, phones)` que envíe a la consola el nombre 61 | y el número de teléfono del usuario. A los parámetros `names` y `phones` se les pasará 62 | cadenas de nombres y números de teléfono, separadas por comas. El índice de los nombres 63 | y números de teléfono en las cadenas indican una coincidencia. Asegúrate de que el número 64 | de nombres y teléfonos sea el mismo. 65 | 66 | ```js 67 | function printContactsInfo(names, phones) {} 68 | 69 | printContactsInfo( 70 | 'Jacob,William,Solomon,Artemis', 71 | '89001234567,89001112233,890055566377,890055566300', 72 | ); 73 | ``` 74 | 75 | ## Ejemplo 6 - Encontrar el elemento más grande 76 | 77 | Escribe una función `findLargestNumber(numbers)` que busque el número 78 | más grande del Array. 79 | 80 | ```js 81 | function findLargestNumber(numbers) {} 82 | 83 | console.log(findLargestNumber([2, 17, 94, 1, 23, 37])); // 94 84 | console.log(findLargestNumber([49, 4, 7, 83, 12])); // 83 85 | ``` 86 | 87 | ## Ejemplo 7 - Valor promedio 88 | 89 | Escriba una función `calAverage()` que tome un número arbitrario de argumentos 90 | y vuelva su valor promedio. Todos los argumentos serán sólo números. 91 | 92 | ```js 93 | function calAverage() {} 94 | 95 | console.log(calAverage(1, 2, 3, 4)); // 2.5 96 | console.log(calAverage(14, 8, 2)); // 8 97 | console.log(calAverage(27, 43, 2, 8, 36)); // 23.2 98 | ``` 99 | 100 | ## Ejemplo 8 - Formato de tiempo 101 | 102 | Escriba una función `formatTime(minutes)` que convierta el valor de 103 | `minutes` (número de minutos) en una cadena con el formato `HH:MM`. 104 | 105 | ```js 106 | const hours = Math.floor(totalMinutes / 60); 107 | const minutes = totalMinutes % 60; 108 | console.log(hours); 109 | console.log(minutes); 110 | 111 | const doubleDigitHours = String(hours).padStart(2, 0); 112 | const doubleDigitMinutes = String(minutes).padStart(2, 0); 113 | console.log(`${doubleDigitHours}:${doubleDigitMinutes}`); 114 | 115 | function formatTime(minutes) {} 116 | 117 | console.log(formatTime(70)); // "01:10" 118 | console.log(formatTime(450)); // "07:30" 119 | console.log(formatTime(1441)); // "24:01" 120 | ``` 121 | 122 | ## Ejemplo 9 - Colección de cursos (includes, indexOf, push, etc.) 123 | 124 | Escriba funciones para manejar una colección de cursos de capacitación `courses`: 125 | 126 | - `addCourse(name)` - añade un curso al final de la colección 127 | - `removeCourse(name)` - elimina un curso de la colección 128 | - `updateCourse(oldName, newName)` - cambia el nombre por uno nuevo 129 | 130 | ```js 131 | const courses = ['HTML', 'CSS', 'JavaScript', 'React', 'PostgreSQL']; 132 | 133 | addCourse('Express'); 134 | console.log(courses); // ['HTML', 'CSS', 'JavaScript', 'React', 'PostgreSQL', 'Express'] 135 | addCourse('CSS'); // 'Usted ya tiene un curso como este' 136 | 137 | removeCourse('React'); 138 | console.log(courses); // ['HTML', 'CSS', 'JavaScript', 'PostgreSQL', 'Express'] 139 | removeCourse('Vue'); // 'No se ha encontrado ningún curso con este nombre' 140 | 141 | updateCourse('Express', 'NestJS'); 142 | console.log(courses); // ['HTML', 'CSS', 'JavaScript', 'PostgreSQL', 'NestJS'] 143 | ``` 144 | -------------------------------------------------------------------------------- /lesson-04/ru.md: -------------------------------------------------------------------------------- 1 | # Модуль 2. Занятие 4. Функции 2 | 3 | ## Example 1 - Индекс массы тела 4 | 5 | Напиши функцию `calcBMI(weight, height)` которая рассчитывает и возвращает 6 | индекс массы тела человека. Для этого необходимо разделить вес в киллограммах на 7 | квадрат высоты человека в метрах. 8 | 9 | Вес и высота будут специально переданы как строки. Нецелые числа могут быть 10 | заданы в виде `24.7` или `24,7`, то есть в качестве разделителя дробной части 11 | может быть запятая. 12 | 13 | Индекс массы тела необходимо округлить до одной цифры после запятой; 14 | 15 | ```js 16 | const bmi = calcBMI('88,3', '1.75'); 17 | console.log(bmi); // 28.8 18 | ``` 19 | 20 | ## Example 2 - Меньшее из чисел 21 | 22 | Напиши функцию `min(a,b)`, которая возвращает меньшее из чисел `a` и `b`. 23 | 24 | ```js 25 | console.log(min(2, 5)); // 2 26 | console.log(min(3, -1)); // -1 27 | console.log(min(1, 1)); // 1 28 | ``` 29 | 30 | ## Example 3 - Площадь прямоугольника 31 | 32 | Напиши функцию `getRectArea(dimensions)` для вычисления площади прямоугольника 33 | со сторонами, значения которых будут переданы в параметр `dimensions` в виде 34 | строки. Значения гарантированно разделены пробелом. 35 | 36 | ```js 37 | function getRectArea(dimensions) {} 38 | 39 | console.log(getRectArea('8 11')); 40 | ``` 41 | 42 | ## Example 4 - Логирование элементов 43 | 44 | Напиши функцию `logItems(items)`, которая получает массив и использует цикл 45 | `for`, который для каждого элемента массива будет выводить в консоль сообщение в 46 | формате `<номер элемента> - <значение элемента>`. Нумерация элементов должна 47 | начинаться с `1`. 48 | 49 | Например для первого элемента массива `['Mango', 'Poly', 'Ajax']` с индексом `0` 50 | будет выведено `1 - Mango`, а для индекса 2 выведет `3 - Ajax`. 51 | 52 | ```js 53 | function logItems(items) {} 54 | 55 | logItems(['Mango', 'Poly', 'Ajax']); 56 | logItems(['🍎', '🍇', '🍑', '🍌', '🍋']); 57 | ``` 58 | 59 | ## Example 5 - Логирование контактов 60 | 61 | Напиши функцию `printContactsInfo(names, phones)` которая выводит в консоль имя 62 | и телефонный номер пользователя. В параметры `names` и `phones` будут переданы 63 | строки имен и телефонных номеров, разделенные запятыми. Порядковый номер имен и 64 | телефонов в строках указывают на соответствие. Количество имен и телефонов 65 | гарантированно одинаковое. 66 | 67 | ```js 68 | function printContactsInfo(names, phones) {} 69 | 70 | printContactsInfo( 71 | 'Jacob,William,Solomon,Artemis', 72 | '89001234567,89001112233,890055566377,890055566300', 73 | ); 74 | ``` 75 | 76 | ## Example 6 - Поиск наибольшего элемента 77 | 78 | Напиши функцию `findLargestNumber(numbers)`которая ищет самое большое число в 79 | массиве. 80 | 81 | ```js 82 | function findLargestNumber(numbers) {} 83 | 84 | console.log(findLargestNumber([2, 17, 94, 1, 23, 37])); // 94 85 | console.log(findLargestNumber([49, 4, 7, 83, 12])); // 83 86 | ``` 87 | 88 | ## Example 7 - Среднее значение 89 | 90 | Напишите функцию `calAverage()` которая принимает произвольное кол-во аргументов 91 | и возвращает их среднее значение. Все аругменты будут только числами. 92 | 93 | ```js 94 | function calAverage() {} 95 | 96 | console.log(calAverage(1, 2, 3, 4)); // 2.5 97 | console.log(calAverage(14, 8, 2)); // 8 98 | console.log(calAverage(27, 43, 2, 8, 36)); // 23.2 99 | ``` 100 | 101 | ## Example 8 - Форматирование времени 102 | 103 | Напиши функцию `formatTime(minutes)` которая переведёт значение `minutes` 104 | (количество минут) в строку в формате часов и минут `HH:MM`. 105 | 106 | ```js 107 | const hours = Math.floor(totalMinutes / 60); 108 | const minutes = totalMinutes % 60; 109 | console.log(hours); 110 | console.log(minutes); 111 | 112 | const doubleDigitHours = String(hours).padStart(2, 0); 113 | const doubleDigitMinutes = String(minutes).padStart(2, 0); 114 | console.log(`${doubleDigitHours}:${doubleDigitMinutes}`); 115 | 116 | function formatTime(minutes) {} 117 | 118 | console.log(formatTime(70)); // "01:10" 119 | console.log(formatTime(450)); // "07:30" 120 | console.log(formatTime(1441)); // "24:01" 121 | ``` 122 | 123 | ## Example 9 - Коллекция курсов (includes, indexOf, push и т. д.) 124 | 125 | Напишите функции для работы с коллекцией обучающих курсов `courses`: 126 | 127 | - `addCourse(name)` - добавляет курс в конец коллекции 128 | - `removeCourse(name)` - удаляет курс из коллекции 129 | - `updateCourse(oldName, newName)` - изменяет имя на новое 130 | 131 | ```js 132 | const courses = ['HTML', 'CSS', 'JavaScript', 'React', 'PostgreSQL']; 133 | 134 | addCourse('Express'); 135 | console.log(courses); // ['HTML', 'CSS', 'JavaScript', 'React', 'PostgreSQL', 'Express'] 136 | addCourse('CSS'); // 'У вас уже есть такой курс' 137 | 138 | removeCourse('React'); 139 | console.log(courses); // ['HTML', 'CSS', 'JavaScript', 'PostgreSQL', 'Express'] 140 | removeCourse('Vue'); // 'Курс с таким имененем не найден' 141 | 142 | updateCourse('Express', 'NestJS'); 143 | console.log(courses); // ['HTML', 'CSS', 'JavaScript', 'PostgreSQL', 'NestJS'] 144 | ``` 145 | -------------------------------------------------------------------------------- /lesson-04/uk.md: -------------------------------------------------------------------------------- 1 | # Модуль 2. Заняття 4. Функції 2 | 3 | ## Example 1 - Індекс маси тіла 4 | 5 | Напиши функцію `calcBMI(weight, height)` яка розраховує та повертає 6 | індекс маси тіла людини. Для цього необхідно розділити вагу в кілограмах на 7 | квадрат висоти людини в метрах. 8 | 9 | Вага та висота будуть спеціально передані як рядки. Не цілі числа можуть бути задані у вигляді 10 | `24.7` або `24,7`, тобто як роздільник дробової частини 11 | може бути кома. 12 | 13 | Індекс маси тіла необхідно округлити до однієї цифри після коми; 14 | 15 | ```js 16 | const bmi = calcBMI('88,3', '1.75'); 17 | console.log(bmi); // 28.8 18 | ``` 19 | 20 | ## Example 2 - Найменше з чисел 21 | 22 | Напиши функцію `min(a,b)`, яка повертає найменше з чисел `a` та `b`. 23 | 24 | ```js 25 | console.log(min(2, 5)); // 2 26 | console.log(min(3, -1)); // -1 27 | console.log(min(1, 1)); // 1 28 | ``` 29 | 30 | ## Example 3 - Площа прямокутника 31 | 32 | Напиши функцію `getRectArea(dimensions)` для обчислення площі прямокутника 33 | зі сторонами, значення яких будуть передані до параметра `dimensions` у вигляді 34 | рядка. Значення гарантовано розділені пробілом. 35 | 36 | ```js 37 | function getRectArea(dimensions) {} 38 | 39 | console.log(getRectArea('8 11')); 40 | ``` 41 | 42 | ## Example 4 - Логування елементів 43 | 44 | Напиши функцію `logItems(items)`, яка отримує масив та використовує цикл 45 | `for`, який для кожного елемента масиву буде виводити в консоль повідомлення у 46 | форматі `<номер елемента> - <значення елемента>`. Нумерація елементів повинна 47 | починатися з `1`. 48 | 49 | Наприклад для першого елемента масиву `['Mango', 'Poly', 'Ajax']` з індексом `0` 50 | буде виведено `1 - Mango`, а для індексу 2 виведе `3 - Ajax`. 51 | 52 | ```js 53 | function logItems(items) {} 54 | 55 | logItems(['Mango', 'Poly', 'Ajax']); 56 | logItems(['🍎', '🍇', '🍑', '🍌', '🍋']); 57 | ``` 58 | 59 | ## Example 5 - Логування контактів 60 | 61 | Напиши функцію `printContactsInfo(names, phones)` яка виводить у консоль ім'я 62 | та телефонний номер користувача. У параметри `names` та `phones` будуть передані 63 | рядки імен та телефонних номерів, розділені комами. Порядковий номер імен та 64 | телефонів у рядках вказують на відповідність. Кількість імен та телефонів 65 | гарантовано однакова. 66 | 67 | ```js 68 | function printContactsInfo(names, phones) {} 69 | 70 | printContactsInfo( 71 | 'Jacob,William,Solomon,Artemis', 72 | '89001234567,89001112233,890055566377,890055566300', 73 | ); 74 | ``` 75 | 76 | ## Example 6 - Пошук найбільшого елемента 77 | 78 | Напиши функцію `findLargestNumber(numbers)`яка шукає найбільше число в 79 | масиві. 80 | 81 | ```js 82 | function findLargestNumber(numbers) {} 83 | 84 | console.log(findLargestNumber([2, 17, 94, 1, 23, 37])); // 94 85 | console.log(findLargestNumber([49, 4, 7, 83, 12])); // 83 86 | ``` 87 | 88 | ## Example 7 - Середнє значення 89 | 90 | Напишіть функцію `calAverage()` яка приймає довільну кількість аргументів 91 | і повертає їхнє середнє значення. Усі аргументи будуть лише числами. 92 | 93 | ```js 94 | function calAverage() {} 95 | 96 | console.log(calAverage(1, 2, 3, 4)); // 2.5 97 | console.log(calAverage(14, 8, 2)); // 8 98 | console.log(calAverage(27, 43, 2, 8, 36)); // 23.2 99 | ``` 100 | 101 | ## Example 8 - Форматування часу 102 | 103 | Напиши функцію `formatTime(minutes)` яка переведе значення `minutes` 104 | (кількість хвилин) у рядок у форматі годин та хвилин `HH:MM`. 105 | 106 | ```js 107 | const hours = Math.floor(totalMinutes / 60); 108 | const minutes = totalMinutes % 60; 109 | console.log(hours); 110 | console.log(minutes); 111 | 112 | const doubleDigitHours = String(hours).padStart(2, 0); 113 | const doubleDigitMinutes = String(minutes).padStart(2, 0); 114 | console.log(`${doubleDigitHours}:${doubleDigitMinutes}`); 115 | 116 | function formatTime(minutes) {} 117 | 118 | console.log(formatTime(70)); // "01:10" 119 | console.log(formatTime(450)); // "07:30" 120 | console.log(formatTime(1441)); // "24:01" 121 | ``` 122 | 123 | ## Example 9 - Колекція курсів (includes, indexOf, push і т. д.) 124 | 125 | Напишіть функції для роботи з колекцією навчальних курсів `courses`: 126 | 127 | - `addCourse(name)` - додає курс до кінця колекції 128 | - `removeCourse(name)` - видаляє курс із колекції 129 | - `updateCourse(oldName, newName)` - змінює ім'я на нове 130 | 131 | ```js 132 | const courses = ['HTML', 'CSS', 'JavaScript', 'React', 'PostgreSQL']; 133 | 134 | addCourse('Express'); 135 | console.log(courses); // ['HTML', 'CSS', 'JavaScript', 'React', 'PostgreSQL', 'Express'] 136 | addCourse('CSS'); // 'Ви вже маєте такий курс' 137 | 138 | removeCourse('React'); 139 | console.log(courses); // ['HTML', 'CSS', 'JavaScript', 'PostgreSQL', 'Express'] 140 | removeCourse('Vue'); // 'Курс із таким ім'ям не знайдено' 141 | 142 | updateCourse('Express', 'NestJS'); 143 | console.log(courses); // ['HTML', 'CSS', 'JavaScript', 'PostgreSQL', 'NestJS'] 144 | ``` 145 | -------------------------------------------------------------------------------- /lesson-05/en.md: -------------------------------------------------------------------------------- 1 | # Module 3. Lesson 1. Objects 2 | 3 | 4 | 5 | ## Example 1 - Object Basics 6 | 7 | Write a script that, for the `user` object, successively: 8 | 9 | - adds a `mood` field with value `'happy'` 10 | - replaces the value `hobby` to `'skydiving'` 11 | - replaces `premium` to `false` 12 | - prints the contents of the `user` object in `key:value` format using 13 | `Object.keys()` and `for...of` 14 | 15 | ### Code 16 | 17 | ```js 18 | const user = { 19 | name: 'Mango', 20 | age: 20, 21 | hobby: 'html', 22 | premium: true, 23 | }; 24 | ``` 25 | 26 | ## Example 2 - Object.values() method 27 | 28 | We have an object that stores our team salaries. Write code for 29 | summing all salaries and store the result in the sum variable. Should 30 | get 390. If the `salaries` object is empty, then the result should be 0. 31 | 32 | ### Code 33 | 34 | ```js 35 | const salaries = { 36 | John: 100, 37 | Ann: 160, 38 | Pete: 130, 39 | }; 40 | ``` 41 | 42 | ## Example 3 - Array of objects 43 | 44 | Write a function `calcTotalPrice(stones, stoneName)` that takes an array 45 | of objects and a string with the name of the stone. The function calculates and returns the total cost 46 | of stones with the same name, price and quantity from the object 47 | ### Code 48 | 49 | ```js 50 | const stones = [ 51 | { name: 'Emerald', price: 1300, quantity: 4 }, 52 | { name: 'Diamond', price: 2700, quantity: 3 }, 53 | { name: 'Sapphire', price: 400, quantity: 7 }, 54 | { name: 'Rubble', price: 200, quantity: 2 }, 55 | ]; 56 | ``` 57 | 58 | ## Example 4 - Complex tasks 59 | 60 | Write a script for managing a personal account of an Internet bank. There is an `account` object 61 | in which it is necessary to implement methods for working with balance and 62 | transaction history. 63 | 64 | ```js 65 | /* 66 | * There are only two types of transaction. 67 | * You can deposit or withdraw money from your account. 68 | */ 69 | const Transaction = { 70 | DEPOSIT: 'deposit', 71 | WITHDRAW: 'withdraw', 72 | }; 73 | 74 | /* 75 | * Each transaction is an object with properties: id, type and amount 76 | */ 77 | 78 | const account = { 79 | // Current account balance 80 | balance: 0, 81 | 82 | // Transaction History 83 | transactions: [], 84 | 85 | /* 86 | * Method creates and returns a transaction object. 87 | * Accepts amount and type of transaction. 88 | */ 89 | createTransaction(amount, type) {}, 90 | 91 | /* 92 | * The method responsible for adding the amount to the balance.. 93 | * Accepts the amount of the transaction. 94 | * Calls createTransaction to create a transaction object 95 | * then adds it to the transaction history 96 | */ 97 | deposit(amount) {}, 98 | 99 | /* 100 | *The method responsible for withdrawing the amount from the balance. 101 | * Принимает сумму танзакции. 102 | * Calls createTransaction to create a transaction object 103 | * then adds it to the transaction history. 104 | * 105 | * If amount is greater than the current balance, display a message 106 | * about the fact that the withdrawal of such an amount is not possible, there are not enough funds. 107 | */ 108 | withdraw(amount) {}, 109 | 110 | /* 111 | * The method returns the current balance 112 | */ 113 | getBalance() {}, 114 | 115 | /* 116 | * The method searches and returns the transaction object by id 117 | */ 118 | getTransactionDetails(id) {}, 119 | 120 | /* 121 | * The method returns the amount of funds 122 | *a specific type of transaction from the entire history of transactions 123 | */ 124 | getTransactionTotal(type) {}, 125 | }; 126 | ``` 127 | -------------------------------------------------------------------------------- /lesson-05/es.md: -------------------------------------------------------------------------------- 1 | # Módulo 3. Clase 1. Objetos 2 | 3 | 4 | 5 | ## Ejemplo 1 - Fundamentos de los objetos 6 | 7 | Escribe un script que, para el objeto `user`, secuencialmente: 8 | 9 | - añade un campo `mood` con el valor `"happy"`. 10 | - sustituye el valor de `hobby` por `'skydiving'`. 11 | - sustituye el valor de `premium` por `false` 12 | - devuelve el contenido del objeto `user` en formato `llave:valor` usando 13 | `Object.keys()` y `for...of` 14 | 15 | ### Código 16 | 17 | ```js 18 | const user = { 19 | name: 'Mango', 20 | age: 20, 21 | hobby: 'html', 22 | premium: true, 23 | }; 24 | ``` 25 | 26 | ## Ejemplo 2 - Método Object.values() 27 | 28 | Tenemos un objeto que almacena los salarios de nuestro equipo. Escribe el código 29 | para sumar todos los salarios y almacenar el resultado en la variable sum. 30 | El resultado debería ser 390. Si el objeto `salaries` está vacío, el resultado debe ser 0. 31 | 32 | ### Código 33 | 34 | ```js 35 | const salaries = { 36 | John: 100, 37 | Ann: 160, 38 | Pete: 130, 39 | }; 40 | ``` 41 | 42 | ## Ejemplo 3 - Array de objetos 43 | 44 | Escribe una función `calcTotalPrice(stones, stoneName)` que tome un array de 45 | objetos y una cadena de nombres de piedras. La función cuenta y devuelve el valor 46 | total de las piedras con ese nombre, precio y cantidad del objeto. 47 | 48 | ### Código 49 | 50 | ```js 51 | const stones = [ 52 | { name: 'Esmeralda', price: 1300, quantity: 4 }, 53 | { name: 'Diamante', price: 2700, quantity: 3 }, 54 | { name: 'Zafiro', price: 400, quantity: 7 }, 55 | { name: 'Piedra triturada', price: 200, quantity: 2 }, 56 | ]; 57 | ``` 58 | 59 | ## Ejemplo 4 - Tareas complejas 60 | 61 | Escribe un script para gestionar una cuenta bancaria online. Existe un 62 | objeto `cuenta` en el que hay que implementar métodos para trabajar con 63 | el saldo y el historial de transacciones. 64 | 65 | ```js 66 | /* 67 | * Sólo hay dos tipos de transacciones. 68 | * Se puede depositar o retirar dinero de la cuenta. 69 | */ 70 | const Transaction = { 71 | DEPOSIT: 'deposit', 72 | WITHDRAW: 'withdraw', 73 | }; 74 | 75 | /* 76 | * Cada transacción es un objeto con propiedades: id, type и amount 77 | */ 78 | 79 | const account = { 80 | // Saldo actual de la cuenta 81 | balance: 0, 82 | 83 | // Historial de transacciones 84 | transactions: [], 85 | 86 | /* 87 | * El método crea y retorna el objeto de la transacción. 88 | * Acepta la suma y el tipo de transacción. 89 | */ 90 | createTransaction(amount, type) {}, 91 | 92 | /* 93 | * Método responsable de añadir el monto al saldo. 94 | * Recibe el monto de la transacción. 95 | * Llama a createTransaction para crear un objeto de transacción 96 | * y después lo añade al historial de transacciones 97 | */ 98 | deposit(amount) {}, 99 | 100 | /* 101 | * El método responsable de retirar el monto del saldo. 102 | * Recibe el monto de la transacción. 103 | * Llama a createTransaction para crear un objeto de transacción 104 | * y después lo añade al historial de transacciones 105 | * 106 | * Si amount es mayor que el saldo actual, imprime un mensaje diciendo 107 | * que, no es posible retirar esta cantidad, no hay fondos suficientes. 108 | */ 109 | withdraw(amount) {}, 110 | 111 | /* 112 | * El método devuelve el saldo actual 113 | */ 114 | getBalance() {}, 115 | 116 | /* 117 | * El método busca y devuelve el objeto de la transacción según su id 118 | */ 119 | getTransactionDetails(id) {}, 120 | 121 | /* 122 | * El método devuelve la cantidad de fondos 123 | * de determinado tipo de transacción de todo el historial de transacciones 124 | */ 125 | getTransactionTotal(type) {}, 126 | }; 127 | ``` 128 | -------------------------------------------------------------------------------- /lesson-05/ru.md: -------------------------------------------------------------------------------- 1 | # Модуль 3. Занятие 1. Объекты 2 | 3 | 4 | 5 | ## Example 1 - Основы обьектов 6 | 7 | Напиши скрипт, который, для объекта `user`, последовательно: 8 | 9 | - добавляет поле `mood` со значением `'happy'` 10 | - заменяет значение `hobby` на `'skydiving'` 11 | - заменяет значение `premium` на `false` 12 | - выводит содержимое объекта `user` в формате `ключ:значение` используя 13 | `Object.keys()` и `for...of` 14 | 15 | ### Код 16 | 17 | ```js 18 | const user = { 19 | name: 'Mango', 20 | age: 20, 21 | hobby: 'html', 22 | premium: true, 23 | }; 24 | ``` 25 | 26 | ## Example 2 - метод Object.values() 27 | 28 | У нас есть объект, в котором хранятся зарплаты нашей команды. Напишите код для 29 | суммирования всех зарплат и сохраните результат в переменной sum. Должно 30 | получиться 390. Если объект `salaries` пуст, то результат должен быть 0. 31 | 32 | ### Код 33 | 34 | ```js 35 | const salaries = { 36 | John: 100, 37 | Ann: 160, 38 | Pete: 130, 39 | }; 40 | ``` 41 | 42 | ## Example 3 - Массив объектов 43 | 44 | Напишите ф-цию `calcTotalPrice(stones, stoneName)`, которая принимает массив 45 | обьектов и строку с названием камня. Ф-ция считает и возвращает общую стоимость 46 | камней с таким именем, ценой и количеством из обьекта 47 | 48 | ### Код 49 | 50 | ```js 51 | const stones = [ 52 | { name: 'Изумруд', price: 1300, quantity: 4 }, 53 | { name: 'Бриллиант', price: 2700, quantity: 3 }, 54 | { name: 'Сапфир', price: 400, quantity: 7 }, 55 | { name: 'Щебень', price: 200, quantity: 2 }, 56 | ]; 57 | ``` 58 | 59 | ## Example 4 - Комплексные задачи 60 | 61 | Напиши скрипт управления личным кабинетом интернет банка. Есть объект `account` 62 | в котором необходимо реализовать методы для работы с балансом и историей 63 | транзакций. 64 | 65 | ```js 66 | /* 67 | * Типов транзацкий всего два. 68 | * Можно положить либо снять деньги со счета. 69 | */ 70 | const Transaction = { 71 | DEPOSIT: 'deposit', 72 | WITHDRAW: 'withdraw', 73 | }; 74 | 75 | /* 76 | * Каждая транзакция это объект со свойствами: id, type и amount 77 | */ 78 | 79 | const account = { 80 | // Текущий баланс счета 81 | balance: 0, 82 | 83 | // История транзакций 84 | transactions: [], 85 | 86 | /* 87 | * Метод создает и возвращает объект транзакции. 88 | * Принимает сумму и тип транзакции. 89 | */ 90 | createTransaction(amount, type) {}, 91 | 92 | /* 93 | * Метод отвечающий за добавление суммы к балансу. 94 | * Принимает сумму танзакции. 95 | * Вызывает createTransaction для создания объекта транзакции 96 | * после чего добавляет его в историю транзакций 97 | */ 98 | deposit(amount) {}, 99 | 100 | /* 101 | * Метод отвечающий за снятие суммы с баланса. 102 | * Принимает сумму танзакции. 103 | * Вызывает createTransaction для создания объекта транзакции 104 | * после чего добавляет его в историю транзакций. 105 | * 106 | * Если amount больше чем текущий баланс, выводи сообщение 107 | * о том, что снятие такой суммы не возможно, недостаточно средств. 108 | */ 109 | withdraw(amount) {}, 110 | 111 | /* 112 | * Метод возвращает текущий баланс 113 | */ 114 | getBalance() {}, 115 | 116 | /* 117 | * Метод ищет и возвращает объект транзации по id 118 | */ 119 | getTransactionDetails(id) {}, 120 | 121 | /* 122 | * Метод возвращает количество средств 123 | * определенного типа транзакции из всей истории транзакций 124 | */ 125 | getTransactionTotal(type) {}, 126 | }; 127 | ``` 128 | -------------------------------------------------------------------------------- /lesson-05/uk.md: -------------------------------------------------------------------------------- 1 | # Модуль 3. Заняття 1. Об'єкти 2 | 3 | 4 | 5 | ## Example 1 - Основи об'єктів 6 | 7 | Напиши скрипт, який для об'єкта `user`, послідовно: 8 | 9 | - додає поле `mood` зі значенням `'happy'` 10 | - замінює значення `hobby` на `'skydiving'` 11 | - замінює значення `premium` на `false` 12 | - виводить вміст об'єкта `user` у форматі `ключ:значення` використовуючи 13 | `Object.keys()` та `for...of` 14 | 15 | ### Код 16 | 17 | ```js 18 | const user = { 19 | name: 'Mango', 20 | age: 20, 21 | hobby: 'html', 22 | premium: true, 23 | }; 24 | ``` 25 | 26 | ## Example 2 - метод Object.values() 27 | 28 | У нас є об'єкт, де зберігаються зарплати нашої команди. Напишіть код для 29 | підсумовування всіх зарплат і збережіть результат у змінній sum. Повинно 30 | вийти 390. Якщо об'єкт `salaries` порожній, то результат має бути 0. 31 | 32 | ### Код 33 | 34 | ```js 35 | const salaries = { 36 | John: 100, 37 | Ann: 160, 38 | Pete: 130, 39 | }; 40 | ``` 41 | 42 | ## Example 3 - Масив об'єктів 43 | 44 | Напишіть функцію `calcTotalPrice(stones, stoneName)`, яка приймає масив 45 | об'єктів та рядок з назвою каменю. Функція рахує і повертає загальну вартість 46 | каміння з таким ім'ям, ціною та кількістю з об'єкта 47 | 48 | ### Код 49 | 50 | ```js 51 | const stones = [ 52 | { name: 'Смарагд', price: 1300, quantity: 4 }, 53 | { name: 'Діамант', price: 2700, quantity: 3 }, 54 | { name: 'Сапфір', price: 400, quantity: 7 }, 55 | { name: 'Щебінь', price: 200, quantity: 2 }, 56 | ]; 57 | ``` 58 | 59 | ## Example 4 - Комплексні завдання 60 | 61 | Напиши скрипт управління особистим кабінетом інтернет банку. Є об'єкт `account` 62 | в якому необхідно реалізувати методи для роботи з балансом та історією 63 | транзакцій. 64 | 65 | ```js 66 | /* 67 | * Типів транзакцій всього два. 68 | * Можна покласти чи зняти гроші з рахунку. 69 | */ 70 | const Transaction = { 71 | DEPOSIT: 'deposit', 72 | WITHDRAW: 'withdraw', 73 | }; 74 | 75 | /* 76 | * Кожна транзакція це об'єкт із властивостями: id, type та amount 77 | */ 78 | 79 | const account = { 80 | // Поточний баланс рахунку 81 | balance: 0, 82 | 83 | // Історія транзакцій 84 | transactions: [], 85 | 86 | /* 87 | * Метод створює та повертає об'єкт транзакції. 88 | * Приймає суму та тип транзакції. 89 | */ 90 | createTransaction(amount, type) {}, 91 | 92 | /* 93 | * Метод, що відповідає за додавання суми до балансу. 94 | * Приймає суму транзакції. 95 | * Викликає createTransaction для створення об'єкта транзакції 96 | * після чого додає його до історії транзакцій 97 | */ 98 | deposit(amount) {}, 99 | 100 | /* 101 | * Метод, що відповідає за зняття суми з балансу. 102 | * Приймає суму транзакції. 103 | * Викликає createTransaction для створення об'єкта транзакції 104 | * після чого додає його до історії транзакцій. 105 | * 106 | * Якщо amount більше ніж поточний баланс, виводь повідомлення 107 | * про те, що зняття такої суми не можливе, недостатньо коштів. 108 | */ 109 | withdraw(amount) {}, 110 | 111 | /* 112 | * Метод повертає поточний баланс 113 | */ 114 | getBalance() {}, 115 | 116 | /* 117 | * Метод шукає та повертає об'єкт транзакції по id 118 | */ 119 | getTransactionDetails(id) {}, 120 | 121 | /* 122 | * Метод повертає кількість коштів 123 | * певного типу транзакції з усієї історії транзакцій 124 | */ 125 | getTransactionTotal(type) {}, 126 | }; 127 | ``` 128 | -------------------------------------------------------------------------------- /lesson-06/en.md: -------------------------------------------------------------------------------- 1 | # Module 3 Lesson 6. Destructuring and rest/spread 2 | 3 | ## Example 1 - Destructuring 4 | 5 | Rewrite the function so that it takes one object of the parameter instead of a set 6 | of independent arguments. 7 | 8 | ```js 9 | function calcBMI(weight, height) { 10 | const numericWeight = Number(weight.replace(',', '.')); 11 | const numericHeight = Number(height.replace(',', '.')); 12 | return Number((numericWeight / numericHeight ** 2).toFixed(1)); 13 | } 14 | 15 | // It was 16 | // console.log(calcBMI('88,3', '1.75')); 17 | // console.log(calcBMI('68,3', '1.65')); 18 | // console.log(calcBMI('118,3', '1.95')); 19 | 20 | // Is expected 21 | console.log( 22 | calcBMI({ 23 | weight: '88,3', 24 | height: '1.75', 25 | }), 26 | ); 27 | console.log( 28 | calcBMI({ 29 | weight: '68,3', 30 | height: '1.65', 31 | }), 32 | ); 33 | console.log( 34 | calcBMI({ 35 | weight: '118,3', 36 | height: '1.95', 37 | }), 38 | ); 39 | ``` 40 | 41 | ## Example 2 - Destructuring 42 | 43 | Rewrite the function so that it takes one object of the parameter instead of a set 44 | of independent arguments. 45 | 46 | ```js 47 | function printContactsInfo(names, phones) { 48 | const nameList = names.split(','); 49 | const phoneList = phones.split(','); 50 | for (let i = 0; i < nameList.length; i += 1) { 51 | console.log(`${nameList[i]}: ${phoneList[i]}`); 52 | } 53 | } 54 | 55 | // It was 56 | // printContactsInfo( 57 | // 'Jacob,William,Solomon,Artemis', 58 | // '89001234567,89001112233,890055566377,890055566300', 59 | // ); 60 | 61 | // Is expected 62 | printContactsInfo({ 63 | names: 'Jacob,William,Solomon,Artemis', 64 | phones: '89001234567,89001112233,890055566377,890055566300', 65 | }); 66 | ``` 67 | 68 | ## Example 3 - Deep destructuring 69 | 70 | Rewrite the property so that it uses one object's parameter instead of a set 71 | of independent arguments. 72 | 73 | ```js 74 | function getBotReport(companyName, repairBots, defenceBots) { 75 | return `${companyName} has ${repairBots + defenceBots} bots in stock`; 76 | } 77 | 78 | // It was 79 | // console.log(getBotReport('Cyberdyne Systems', 150, 50)); 80 | 81 | // Is expected 82 | console.log( 83 | getBotReport({ 84 | companyName: 'Cyberdyne Systems', 85 | bots: { 86 | repair: 150, 87 | defence: 50, 88 | }, 89 | }), 90 | ); // "Cyberdyne Systems has 200 bots in stock" 91 | ``` 92 | 93 | ## Example 4 - Destructuring 94 | 95 | Rewrite the function so that it accepts a parameters object with properties 96 | `companyName` and `stock` and display a report abou the number of goods in the warehouse 97 | of any companies. 98 | 99 | 100 | ```js 101 | // Solution 102 | function getStockReport({ companyName, stock }) { 103 | let total = 0; 104 | for (const value of Object.values(stock)) { 105 | total += value; 106 | } 107 | return `${companyName} has ${total} items in stock`; 108 | } 109 | 110 | console.log( 111 | getStockReport({ 112 | companyName: 'Cyberdyne Systems', 113 | stock: { 114 | repairBots: 150, 115 | defenceBots: 50, 116 | }, 117 | }), 118 | ); // "Cyberdyne Systems has 200 items in stock" 119 | 120 | console.log( 121 | getStockReport({ 122 | companyName: 'Belacci', 123 | stock: { 124 | shoes: 20, 125 | skirts: 10, 126 | hats: 5, 127 | }, 128 | }), 129 | ); // "Belacci has 35 item in stock" 130 | ``` 131 | 132 | ## Example 5 - operation Spread 133 | 134 | Extend the `createContact(partialContact)` function so that it returns a new 135 | contact object with `id` and `createdAt` properties added, as well as `list` with 136 | value "default" if there is no such property in `partialContact`. 137 | 138 | ```js 139 | // Solution 140 | function createContact(partialContact) { 141 | return { 142 | list: 'default', 143 | ...partialContact, 144 | id: generateId(), 145 | createdAt: Date.now(), 146 | }; 147 | } 148 | 149 | console.log( 150 | createContact({ 151 | name: 'Mango', 152 | email: 'mango@mail.com', 153 | list: 'friends', 154 | }), 155 | ); 156 | console.log( 157 | createContact({ 158 | name: 'Poly', 159 | email: 'poly@hotmail.com', 160 | }), 161 | ); 162 | 163 | function generateId() { 164 | return '_' + Math.random().toString(36).substr(2, 9); 165 | } 166 | ``` 167 | 168 | ## Example 6 - Operation rest 169 | 170 | Write a `transformUsername(user)` function to return a new object 171 | with `fullName` property instead of `firstName` and `lastName`. 172 | 173 | ```js 174 | // Solution 175 | function transformUsername({ firstName, lastName, ...otherProps }) { 176 | return { 177 | fullName: `${firstName} ${lastName}`, 178 | ...otherProps, 179 | }; 180 | } 181 | 182 | console.log( 183 | transformId({ 184 | id: 1, 185 | firstName: 'Jacob', 186 | lastName: 'Mercer', 187 | email: 'j.mercer@mail.com', 188 | friendCount: 40, 189 | }), 190 | ); 191 | 192 | console.log( 193 | transformId({ 194 | id: 2, 195 | firstName: 'Adrian', 196 | lastName: 'Cross', 197 | email: 'a.cross@hotmail.com', 198 | friendCount: 20, 199 | }), 200 | ); 201 | ``` 202 | -------------------------------------------------------------------------------- /lesson-06/es.md: -------------------------------------------------------------------------------- 1 | # Módulo 3. Clase 6. Desestructuración y rest/spread 2 | 3 | ## Ejemplo 1 - Desestructuración 4 | 5 | Reescribe la función para que acepte un único objeto de parámetros en lugar 6 | de un conjunto de argumentos independientes. 7 | 8 | ```js 9 | function calcBMI(weight, height) { 10 | const numericWeight = Number(weight.replace(',', '.')); 11 | const numericHeight = Number(height.replace(',', '.')); 12 | return Number((numericWeight / numericHeight ** 2).toFixed(1)); 13 | } 14 | 15 | // Era 16 | // console.log(calcBMI('88,3', '1.75')); 17 | // console.log(calcBMI('68,3', '1.65')); 18 | // console.log(calcBMI('118,3', '1.95')); 19 | 20 | // Se espera 21 | console.log( 22 | calcBMI({ 23 | weight: '88,3', 24 | height: '1.75', 25 | }), 26 | ); 27 | console.log( 28 | calcBMI({ 29 | weight: '68,3', 30 | height: '1.65', 31 | }), 32 | ); 33 | console.log( 34 | calcBMI({ 35 | weight: '118,3', 36 | height: '1.95', 37 | }), 38 | ); 39 | ``` 40 | 41 | ## Ejemplo 2 - Desestructuración 42 | 43 | Reescribe la función para que acepte un único objeto de parámetros en lugar 44 | de un conjunto de argumentos independientes. 45 | 46 | ```js 47 | function printContactsInfo(names, phones) { 48 | const nameList = names.split(','); 49 | const phoneList = phones.split(','); 50 | for (let i = 0; i < nameList.length; i += 1) { 51 | console.log(`${nameList[i]}: ${phoneList[i]}`); 52 | } 53 | } 54 | 55 | // Era 56 | // printContactsInfo( 57 | // 'Jacob,William,Solomon,Artemis', 58 | // '89001234567,89001112233,890055566377,890055566300', 59 | // ); 60 | 61 | // Se espera 62 | printContactsInfo({ 63 | names: 'Jacob,William,Solomon,Artemis', 64 | phones: '89001234567,89001112233,890055566377,890055566300', 65 | }); 66 | ``` 67 | 68 | ## Ejemplo 3 - Desestructuración profunda 69 | 70 | Reescribe la función para que acepte un único objeto de parámetros en lugar 71 | de un conjunto de argumentos independientes. 72 | 73 | ```js 74 | function getBotReport(companyName, repairBots, defenceBots) { 75 | return `${companyName} has ${repairBots + defenceBots} bots in stock`; 76 | } 77 | 78 | // Era 79 | // console.log(getBotReport('Cyberdyne Systems', 150, 50)); 80 | 81 | // Se espera 82 | console.log( 83 | getBotReport({ 84 | companyName: 'Cyberdyne Systems', 85 | bots: { 86 | repair: 150, 87 | defence: 50, 88 | }, 89 | }), 90 | ); // "Cyberdyne Systems has 200 bots in stock" 91 | ``` 92 | 93 | ## Example 4 - Desestructuración 94 | 95 | Reescriba la función para que acepte un objeto parámetro con las 96 | propiedades `companyName` y `stock` y produzca un informe sobre 97 | la cantidad de productos en stock para cualquier empresa. 98 | 99 | ```js 100 | // Solución 101 | function getStockReport({ companyName, stock }) { 102 | let total = 0; 103 | for (const value of Object.values(stock)) { 104 | total += value; 105 | } 106 | return `${companyName} has ${total} items in stock`; 107 | } 108 | 109 | console.log( 110 | getStockReport({ 111 | companyName: 'Cyberdyne Systems', 112 | stock: { 113 | repairBots: 150, 114 | defenceBots: 50, 115 | }, 116 | }), 117 | ); // "Cyberdyne Systems has 200 items in stock" 118 | 119 | console.log( 120 | getStockReport({ 121 | companyName: 'Belacci', 122 | stock: { 123 | shoes: 20, 124 | skirts: 10, 125 | hats: 5, 126 | }, 127 | }), 128 | ); // "Belacci has 35 item in stock" 129 | ``` 130 | 131 | ## Ejemplo 5 - Operación spread 132 | 133 | Completa la función `createContact(partialContact)` para que devuelva un nuevo 134 | objeto de contacto con las propiedades añadidas `id` y `createdAt` así como `list` con 135 | el valor "default" si `partialContact` no tiene dicha propiedad. 136 | 137 | ```js 138 | // Solución 139 | function createContact(partialContact) { 140 | return { 141 | list: 'default', 142 | ...partialContact, 143 | id: generateId(), 144 | createdAt: Date.now(), 145 | }; 146 | } 147 | 148 | console.log( 149 | createContact({ 150 | name: 'Mango', 151 | email: 'mango@mail.com', 152 | list: 'friends', 153 | }), 154 | ); 155 | console.log( 156 | createContact({ 157 | name: 'Poly', 158 | email: 'poly@hotmail.com', 159 | }), 160 | ); 161 | 162 | function generateId() { 163 | return '_' + Math.random().toString(36).substr(2, 9); 164 | } 165 | ``` 166 | 167 | ## Ejemplo 6 - Operación rest 168 | 169 | Escribe la función `transformUsername(user)` para que devuelva un nuevo objeto 170 | con la propiedad `fullName`, en lugar de `firstName` y `lastName`. 171 | 172 | ```js 173 | // Solución 174 | function transformUsername({ firstName, lastName, ...otherProps }) { 175 | return { 176 | fullName: `${firstName} ${lastName}`, 177 | ...otherProps, 178 | }; 179 | } 180 | 181 | console.log( 182 | transformId({ 183 | id: 1, 184 | firstName: 'Jacob', 185 | lastName: 'Mercer', 186 | email: 'j.mercer@mail.com', 187 | friendCount: 40, 188 | }), 189 | ); 190 | 191 | console.log( 192 | transformId({ 193 | id: 2, 194 | firstName: 'Adrian', 195 | lastName: 'Cross', 196 | email: 'a.cross@hotmail.com', 197 | friendCount: 20, 198 | }), 199 | ); 200 | ``` 201 | -------------------------------------------------------------------------------- /lesson-06/ru.md: -------------------------------------------------------------------------------- 1 | # Модуль 3 Занятие 6. Деструктуризация и rest/spread 2 | 3 | ## Example 1 - Деструктуризация 4 | 5 | Перепиши функцию так, чтобы она принимала один объект параметров, вместо набора 6 | независимых аргументов. 7 | 8 | ```js 9 | function calcBMI(weight, height) { 10 | const numericWeight = Number(weight.replace(',', '.')); 11 | const numericHeight = Number(height.replace(',', '.')); 12 | return Number((numericWeight / numericHeight ** 2).toFixed(1)); 13 | } 14 | 15 | // Было 16 | // console.log(calcBMI('88,3', '1.75')); 17 | // console.log(calcBMI('68,3', '1.65')); 18 | // console.log(calcBMI('118,3', '1.95')); 19 | 20 | // Ожидается 21 | console.log( 22 | calcBMI({ 23 | weight: '88,3', 24 | height: '1.75', 25 | }), 26 | ); 27 | console.log( 28 | calcBMI({ 29 | weight: '68,3', 30 | height: '1.65', 31 | }), 32 | ); 33 | console.log( 34 | calcBMI({ 35 | weight: '118,3', 36 | height: '1.95', 37 | }), 38 | ); 39 | ``` 40 | 41 | ## Example 2 - Деструктуризация 42 | 43 | Перепиши функцию так, чтобы она принимала один объект параметров, вместо набора 44 | независимых аргументов. 45 | 46 | ```js 47 | function printContactsInfo(names, phones) { 48 | const nameList = names.split(','); 49 | const phoneList = phones.split(','); 50 | for (let i = 0; i < nameList.length; i += 1) { 51 | console.log(`${nameList[i]}: ${phoneList[i]}`); 52 | } 53 | } 54 | 55 | // Было 56 | // printContactsInfo( 57 | // 'Jacob,William,Solomon,Artemis', 58 | // '89001234567,89001112233,890055566377,890055566300', 59 | // ); 60 | 61 | // Ожидается 62 | printContactsInfo({ 63 | names: 'Jacob,William,Solomon,Artemis', 64 | phones: '89001234567,89001112233,890055566377,890055566300', 65 | }); 66 | ``` 67 | 68 | ## Example 3 - Глубокая деструктуризация 69 | 70 | Перепиши функцию так, чтобы она принимала один объект параметров, вместо набора 71 | независимых аргументов. 72 | 73 | ```js 74 | function getBotReport(companyName, repairBots, defenceBots) { 75 | return `${companyName} has ${repairBots + defenceBots} bots in stock`; 76 | } 77 | 78 | // Было 79 | // console.log(getBotReport('Cyberdyne Systems', 150, 50)); 80 | 81 | // Ожидается 82 | console.log( 83 | getBotReport({ 84 | companyName: 'Cyberdyne Systems', 85 | bots: { 86 | repair: 150, 87 | defence: 50, 88 | }, 89 | }), 90 | ); // "Cyberdyne Systems has 200 bots in stock" 91 | ``` 92 | 93 | ## Example 4 - Деструктуризация 94 | 95 | Перепиши функцию так, чтобы она принимала объект параметров со свойствами 96 | `companyName` и `stock` и выводила репорт о количестве товаров на складе любой 97 | компании. 98 | 99 | ```js 100 | // Решение 101 | function getStockReport({ companyName, stock }) { 102 | let total = 0; 103 | for (const value of Object.values(stock)) { 104 | total += value; 105 | } 106 | return `${companyName} has ${total} items in stock`; 107 | } 108 | 109 | console.log( 110 | getStockReport({ 111 | companyName: 'Cyberdyne Systems', 112 | stock: { 113 | repairBots: 150, 114 | defenceBots: 50, 115 | }, 116 | }), 117 | ); // "Cyberdyne Systems has 200 items in stock" 118 | 119 | console.log( 120 | getStockReport({ 121 | companyName: 'Belacci', 122 | stock: { 123 | shoes: 20, 124 | skirts: 10, 125 | hats: 5, 126 | }, 127 | }), 128 | ); // "Belacci has 35 item in stock" 129 | ``` 130 | 131 | ## Example 5 - Операция spread 132 | 133 | Дополни функцию `createContact(partialContact)` так, чтобы она возвращала новый 134 | объект контакта с добавленными свойствами `id` и `createdAt`, а также `list` со 135 | значением "default" если в `partialContact` нет такого свойства. 136 | 137 | ```js 138 | // Решение 139 | function createContact(partialContact) { 140 | return { 141 | list: 'default', 142 | ...partialContact, 143 | id: generateId(), 144 | createdAt: Date.now(), 145 | }; 146 | } 147 | 148 | console.log( 149 | createContact({ 150 | name: 'Mango', 151 | email: 'mango@mail.com', 152 | list: 'friends', 153 | }), 154 | ); 155 | console.log( 156 | createContact({ 157 | name: 'Poly', 158 | email: 'poly@hotmail.com', 159 | }), 160 | ); 161 | 162 | function generateId() { 163 | return '_' + Math.random().toString(36).substr(2, 9); 164 | } 165 | ``` 166 | 167 | ## Example 6 - Операция rest 168 | 169 | Напиши функцию `transformUsername(user)` так, чтобы она возвращала новый обьект 170 | со свойством `fullName`, вместо `firstName` и `lastName`. 171 | 172 | ```js 173 | // Решение 174 | function transformUsername({ firstName, lastName, ...otherProps }) { 175 | return { 176 | fullName: `${firstName} ${lastName}`, 177 | ...otherProps, 178 | }; 179 | } 180 | 181 | console.log( 182 | transformId({ 183 | id: 1, 184 | firstName: 'Jacob', 185 | lastName: 'Mercer', 186 | email: 'j.mercer@mail.com', 187 | friendCount: 40, 188 | }), 189 | ); 190 | 191 | console.log( 192 | transformId({ 193 | id: 2, 194 | firstName: 'Adrian', 195 | lastName: 'Cross', 196 | email: 'a.cross@hotmail.com', 197 | friendCount: 20, 198 | }), 199 | ); 200 | ``` 201 | -------------------------------------------------------------------------------- /lesson-06/uk.md: -------------------------------------------------------------------------------- 1 | # Модуль 3 Заняття 6. Деструктуризація та rest/spread 2 | 3 | ## Example 1 - Деструктуризація 4 | 5 | Перепиши функцію так, щоб вона приймала один об'єкт параметрів замість набору 6 | незалежних аргументів. 7 | 8 | ```js 9 | function calcBMI(weight, height) { 10 | const numericWeight = Number(weight.replace(',', '.')); 11 | const numericHeight = Number(height.replace(',', '.')); 12 | return Number((numericWeight / numericHeight ** 2).toFixed(1)); 13 | } 14 | 15 | // Було 16 | // console.log(calcBMI('88,3', '1.75')); 17 | // console.log(calcBMI('68,3', '1.65')); 18 | // console.log(calcBMI('118,3', '1.95')); 19 | 20 | // Очікується 21 | console.log( 22 | calcBMI({ 23 | weight: '88,3', 24 | height: '1.75', 25 | }), 26 | ); 27 | console.log( 28 | calcBMI({ 29 | weight: '68,3', 30 | height: '1.65', 31 | }), 32 | ); 33 | console.log( 34 | calcBMI({ 35 | weight: '118,3', 36 | height: '1.95', 37 | }), 38 | ); 39 | ``` 40 | 41 | ## Example 2 - Деструктуризація 42 | 43 | Перепиши функцію так, щоб вона приймала один об'єкт параметрів замість набору 44 | незалежних аргументів. 45 | 46 | ```js 47 | function printContactsInfo(names, phones) { 48 | const nameList = names.split(','); 49 | const phoneList = phones.split(','); 50 | for (let i = 0; i < nameList.length; i += 1) { 51 | console.log(`${nameList[i]}: ${phoneList[i]}`); 52 | } 53 | } 54 | 55 | // Було 56 | // printContactsInfo( 57 | // 'Jacob,William,Solomon,Artemis', 58 | // '89001234567,89001112233,890055566377,890055566300', 59 | // ); 60 | 61 | // Очікується 62 | printContactsInfo({ 63 | names: 'Jacob,William,Solomon,Artemis', 64 | phones: '89001234567,89001112233,890055566377,890055566300', 65 | }); 66 | ``` 67 | 68 | ## Example 3 - Глибока деструктуризація 69 | 70 | Перепиши функцію так, щоб вона приймала один об'єкт параметрів замість набору 71 | незалежних аргументів. 72 | 73 | ```js 74 | function getBotReport(companyName, repairBots, defenceBots) { 75 | return `${companyName} has ${repairBots + defenceBots} bots in stock`; 76 | } 77 | 78 | // Було 79 | // console.log(getBotReport('Cyberdyne Systems', 150, 50)); 80 | 81 | // Очікується 82 | console.log( 83 | getBotReport({ 84 | companyName: 'Cyberdyne Systems', 85 | bots: { 86 | repair: 150, 87 | defence: 50, 88 | }, 89 | }), 90 | ); // "Cyberdyne Systems has 200 bots in stock" 91 | ``` 92 | 93 | ## Example 4 - Деструктуризація 94 | 95 | Перепиши функцію так, щоб вона приймала об'єкт параметрів із властивостями 96 | `companyName` та `stock` та виводила репорт про кількість товарів на складі будь-якої 97 | компанії. 98 | 99 | ```js 100 | // Рішення 101 | function getStockReport({ companyName, stock }) { 102 | let total = 0; 103 | for (const value of Object.values(stock)) { 104 | total += value; 105 | } 106 | return `${companyName} has ${total} items in stock`; 107 | } 108 | 109 | console.log( 110 | getStockReport({ 111 | companyName: 'Cyberdyne Systems', 112 | stock: { 113 | repairBots: 150, 114 | defenceBots: 50, 115 | }, 116 | }), 117 | ); // "Cyberdyne Systems has 200 items in stock" 118 | 119 | console.log( 120 | getStockReport({ 121 | companyName: 'Belacci', 122 | stock: { 123 | shoes: 20, 124 | skirts: 10, 125 | hats: 5, 126 | }, 127 | }), 128 | ); // "Belacci has 35 item in stock" 129 | ``` 130 | 131 | ## Example 5 - Операція spread 132 | 133 | Доповни функцію `createContact(partialContact)` так, щоб вона повертала новий 134 | об'єкт контакту з доданими властивостями `id` та `createdAt`, а також `list` зі 135 | значенням "default" якщо в `partialContact` немає такої властивості. 136 | 137 | ```js 138 | // Рішення 139 | function createContact(partialContact) { 140 | return { 141 | list: 'default', 142 | ...partialContact, 143 | id: generateId(), 144 | createdAt: Date.now(), 145 | }; 146 | } 147 | 148 | console.log( 149 | createContact({ 150 | name: 'Mango', 151 | email: 'mango@mail.com', 152 | list: 'friends', 153 | }), 154 | ); 155 | console.log( 156 | createContact({ 157 | name: 'Poly', 158 | email: 'poly@hotmail.com', 159 | }), 160 | ); 161 | 162 | function generateId() { 163 | return '_' + Math.random().toString(36).substr(2, 9); 164 | } 165 | ``` 166 | 167 | ## Example 6 - Операція rest 168 | 169 | Напиши функцію `transformUsername(user)` так, щоб вона повертала новий об'єкт із властивістю 170 | `fullName`, замість `firstName` та `lastName`. 171 | 172 | ```js 173 | // Рішення 174 | function transformUsername({ firstName, lastName, ...otherProps }) { 175 | return { 176 | fullName: `${firstName} ${lastName}`, 177 | ...otherProps, 178 | }; 179 | } 180 | 181 | console.log( 182 | transformId({ 183 | id: 1, 184 | firstName: 'Jacob', 185 | lastName: 'Mercer', 186 | email: 'j.mercer@mail.com', 187 | friendCount: 40, 188 | }), 189 | ); 190 | 191 | console.log( 192 | transformId({ 193 | id: 2, 194 | firstName: 'Adrian', 195 | lastName: 'Cross', 196 | email: 'a.cross@hotmail.com', 197 | friendCount: 20, 198 | }), 199 | ); 200 | ``` 201 | -------------------------------------------------------------------------------- /lesson-07/en.md: -------------------------------------------------------------------------------- 1 | # Module 4. Lesson 7. Callbacks. Arrow functions. forEach 2 | 3 | ## Example 1 - Function callback 4 | 5 | Write the following functions: 6 | 7 | - `createProduct(obj, callback)` - accepts a product object without an id, and also 8 | callback. The function creates a product object by adding a unique identifier to it in 9 | property `id` and calls the callback passing it the created object. 10 | - `logProduct(product)` - callback accepting a product object and logging it to 11 | console 12 | - `logTotalPrice(product)` - callback receiving product object and logging 13 | the total value of the item in the console 14 | 15 | ```js 16 | // Solution 17 | function createProduct(partialProduct, callback) { 18 | const product = { id: Date.now(), ...partialProduct }; 19 | callback(product); 20 | } 21 | 22 | function logProduct(product) { 23 | console.log(product); 24 | } 25 | 26 | function logTotalPrice(product) { 27 | console.log(product.price * product.quantity); 28 | } 29 | 30 | createProduct({ name: '🍎', price: 30, quantity: 3 }, logProduct); 31 | createProduct({ name: '🍋', price: 20, quantity: 5 }, logTotalPrice); 32 | ``` 33 | 34 | ## Example 2 - Function callback 35 | 36 | Add methods `withdraw(amount, onSuccess, onError)` to the `account` object and 37 | `deposit(amount, onSuccess, onError)`, where the first parameter is the amount of the operation, and 38 | second and third are callbacks. 39 | 40 | The `withdraw` method raises onError if amount is greater than TRANSACTION_LIMIT or 41 | this.balance, and onSuccess otherwise. 42 | `deposit` method raises onError if amount is greater than TRANSACTION_LIMIT or less 43 | or either zero and onSuccess otherwise. 44 | 45 | ```js 46 | // Solution 47 | const TRANSACTION_LIMIT = 1000; 48 | 49 | const account = { 50 | username: 'Jacob', 51 | balance: 400, 52 | withdraw(amount, onSuccess, onError) { 53 | if (amount > TRANSACTION_LIMIT) { 54 | onError(`Amount should not exceed ${TRANSACTION_LIMIT} credits`); 55 | } else if (amount > this.balance) { 56 | onError(`Amount can't exceed account balance of ${this.balance} credits`); 57 | } else { 58 | this.balance -= amount; 59 | onSuccess(`Account balance: ${this.balance}`); 60 | } 61 | }, 62 | deposit(amount, onSuccess, onError) { 63 | if (amount > TRANSACTION_LIMIT) { 64 | onError(`Amount should not exceed ${TRANSACTION_LIMIT} credits`); 65 | } else if (amount <= 0) { 66 | onError(`Amount must be more than 0 credits`); 67 | } else { 68 | this.balance += amount; 69 | onSuccess(`Account balance: ${this.balance}`); 70 | } 71 | }, 72 | }; 73 | 74 | function handleSuccess(message) { 75 | console.log(`✅ Success! ${message}`); 76 | } 77 | function handleError(message) { 78 | console.log(`❌ Error! ${message}`); 79 | } 80 | 81 | account.withdraw(2000, handleSuccess, handleError); 82 | account.withdraw(600, handleSuccess, handleError); 83 | account.withdraw(300, handleSuccess, handleError); 84 | account.deposit(1700, handleSuccess, handleError); 85 | account.deposit(0, handleSuccess, handleError); 86 | account.deposit(-600, handleSuccess, handleError); 87 | account.deposit(600, handleSuccess, handleError); 88 | ``` 89 | 90 | ## Example 3 - Function callback 91 | 92 | Write a function `each(array, callback)` that takes as its first parameter 93 | array, and the second - a function that will be applied to each element of the array. 94 | The each function must return a new array whose elements will be the results 95 | of callback call. 96 | 97 | ```js 98 | // Solution 99 | function each(array, callback) { 100 | const newArr = []; 101 | for (const el of array) { 102 | newArr.push(callback(el)); 103 | } 104 | return newArr; 105 | } 106 | 107 | console.log( 108 | each([64, 49, 36, 25, 16], function (value) { 109 | return value * 2; 110 | }), 111 | ); 112 | console.log( 113 | each([64, 49, 36, 25, 16], function (value) { 114 | return value - 10; 115 | }), 116 | ); 117 | console.log( 118 | each([64, 49, 36, 25, 16], function (value) { 119 | return Math.sqrt(value); 120 | }), 121 | ); 122 | console.log( 123 | each([1.5, 2.1, 16.4, 9.7, 11.3], function (value) { 124 | return Math.ceil(value); 125 | }), 126 | ); 127 | console.log( 128 | each([1.5, 2.1, 16.4, 9.7, 11.3], function (value) { 129 | return Math.floor(value); 130 | }), 131 | ); 132 | ``` 133 | 134 | ## Example 4 - Arrow functions 135 | Make the code refactoring using arrow functions. 136 | 137 | ```js 138 | function createProduct(partialProduct, callback) { 139 | const product = { id: Date.now(), ...partialProduct }; 140 | callback(product); 141 | } 142 | 143 | function logProduct(product) { 144 | console.log(product); 145 | } 146 | 147 | function logTotalPrice(product) { 148 | console.log(product.price * product.quantity); 149 | } 150 | 151 | createProduct({ name: '🍎', price: 30, quantity: 3 }, logProduct); 152 | createProduct({ name: '🍋', price: 20, quantity: 5 }, logTotalPrice); 153 | ``` 154 | 155 | ## Example 5 - Arrow functions 156 | 157 | Make the code refactoring using arrow functions. 158 | 159 | ```js 160 | const TRANSACTION_LIMIT = 1000; 161 | 162 | const account = { 163 | username: 'Jacob', 164 | balance: 400, 165 | withdraw(amount, onSuccess, onError) { 166 | if (amount > TRANSACTION_LIMIT) { 167 | onError(`Amount should not exceed ${TRANSACTION_LIMIT} credits`); 168 | } else if (amount > this.balance) { 169 | onError(`Amount can't exceed account balance of ${this.balance} credits`); 170 | } else { 171 | this.balance -= amount; 172 | onSuccess(`Account balance: ${this.balance}`); 173 | } 174 | }, 175 | deposit(amount, onSuccess, onError) { 176 | if (amount > TRANSACTION_LIMIT) { 177 | onError(`Amount should not exceed ${TRANSACTION_LIMIT} credits`); 178 | } else if (amount <= 0) { 179 | onError(`Amount must be more than 0 credits`); 180 | } else { 181 | this.balance += amount; 182 | onSuccess(`Account balance: ${this.balance}`); 183 | } 184 | }, 185 | }; 186 | 187 | function handleSuccess(message) { 188 | console.log(`✅ Success! ${message}`); 189 | } 190 | function handleError(message) { 191 | console.log(`❌ Error! ${message}`); 192 | } 193 | 194 | account.withdraw(2000, handleSuccess, handleError); 195 | account.withdraw(600, handleSuccess, handleError); 196 | account.withdraw(300, handleSuccess, handleError); 197 | account.deposit(1700, handleSuccess, handleError); 198 | account.deposit(0, handleSuccess, handleError); 199 | account.deposit(-600, handleSuccess, handleError); 200 | account.deposit(600, handleSuccess, handleError); 201 | ``` 202 | 203 | ## Example 6 - Inline Arrow Functions 204 | 205 | Make the code refactoring using arrow functions. 206 | 207 | ```js 208 | function each(array, callback) { 209 | const newArr = []; 210 | for (const el of array) { 211 | newArr.push(callback(el)); 212 | } 213 | return newArr; 214 | } 215 | 216 | console.log( 217 | each([64, 49, 36, 25, 16], function (value) { 218 | return value * 2; 219 | }), 220 | ); 221 | console.log( 222 | each([64, 49, 36, 25, 16], function (value) { 223 | return value - 10; 224 | }), 225 | ); 226 | console.log( 227 | each([64, 49, 36, 25, 16], function (value) { 228 | return Math.sqrt(value); 229 | }), 230 | ); 231 | console.log( 232 | each([1.5, 2.1, 16.4, 9.7, 11.3], function (value) { 233 | return Math.ceil(value); 234 | }), 235 | ); 236 | console.log( 237 | each([1.5, 2.1, 16.4, 9.7, 11.3], function (value) { 238 | return Math.floor(value); 239 | }), 240 | ); 241 | ``` 242 | 243 | ## Example 7 - forEach method 244 | 245 | Make the code refactoring using `forEach` method and arrow functions. 246 | 247 | ```js 248 | function logItems(items) { 249 | console.log(items); 250 | for (let i = 0; i < items.length; i += 1) { 251 | console.log(`${i + 1} - ${items[i]}`); 252 | } 253 | } 254 | 255 | logItems(['Mango', 'Poly', 'Ajax']); 256 | logItems(['🍎', '🍇', '🍑', '🍌', '🍋']); 257 | ``` 258 | 259 | ## Example 8 - forEach method 260 | 261 | 262 | Make the code refactoring using `forEach` method and arrow functions. 263 | 264 | ```js 265 | function printContactsInfo({ names, phones }) { 266 | const nameList = names.split(','); 267 | const phoneList = phones.split(','); 268 | for (let i = 0; i < nameList.length; i += 1) { 269 | console.log(`${nameList[i]}: ${phoneList[i]}`); 270 | } 271 | } 272 | 273 | printContactsInfo({ 274 | names: 'Jacob,William,Solomon,Artemis', 275 | phones: '89001234567,89001112233,890055566377,890055566300', 276 | }); 277 | ``` 278 | 279 | ## Example 9 - forEach method 280 | 281 | Make the code refactoring using `forEach` method and arrow functions. 282 | 283 | ```js 284 | function calсulateAverage(...args) { 285 | let total = 0; 286 | for (let i = 0; i < args.length; i++) { 287 | total += args[i]; 288 | } 289 | return total / args.length; 290 | } 291 | 292 | console.log(calсulateAverage(1, 2, 3, 4)); // 2.5 293 | console.log(calсulateAverage(14, 8, 2)); // 8 294 | console.log(calсulateAverage(27, 43, 2, 8, 36)); // 23.2 295 | ``` 296 | -------------------------------------------------------------------------------- /lesson-07/es.md: -------------------------------------------------------------------------------- 1 | # Módulo 4. Clase 7. CallBacks. Funciones de Flecha. forEach 2 | 3 | ## Ejemplo 1 - Funciones CallBack 4 | 5 | Escriba las siguientes funciones: 6 | 7 | - `createProduct(obj, callback)` - acepta un objeto de producto sin id, así como una CallBack. 8 | La función crea un objeto de producto añadiendo un identificador único a su propiedad `id` y 9 | llama al la CallBack, pasándole el objeto creado. 10 | - `logProduct(product)` - callback que recibe un objeto de producto y lo registra 11 | en el consola 12 | - `logTotalPrice(product)` - callback que recibe un objeto de producto y registra 13 | el coste total del producto en la consola 14 | 15 | ```js 16 | // solución 17 | function createProduct(partialProduct, callback) { 18 | const product = { id: Date.now(), ...partialProduct }; 19 | callback(product); 20 | } 21 | 22 | function logProduct(product) { 23 | console.log(product); 24 | } 25 | 26 | function logTotalPrice(product) { 27 | console.log(product.price * product.quantity); 28 | } 29 | 30 | createProduct({ name: '🍎', price: 30, quantity: 3 }, logProduct); 31 | createProduct({ name: '🍋', price: 20, quantity: 5 }, logTotalPrice); 32 | ``` 33 | 34 | ## Ejemplo 2 - Funciones CallBack 35 | 36 | Agregue un objeto `account` métodos `withdraw(amount, onSuccess, onError)` y 37 | `deposit(amount, onSuccess, onError)`, donde el primer parámetro es la suma de la 38 | operación y el segundo y el tercero son las CallBacks. 39 | 40 | El método `withdraw` devuelve onError si el monto es mayor que TRANSACTION_LIMIT o 41 | this.balance, y en caso contrario onSuccess. 42 | 43 | EL método `deposit` devuelve onError si el monto el mayor que TRANSACTION_LIMIT o menor 44 | o igual a 0, y en caso contrario onSuccess. 45 | 46 | ```js 47 | // Solución 48 | const TRANSACTION_LIMIT = 1000; 49 | 50 | const account = { 51 | username: 'Jacob', 52 | balance: 400, 53 | withdraw(amount, onSuccess, onError) { 54 | if (amount > TRANSACTION_LIMIT) { 55 | onError(`Amount should not exceed ${TRANSACTION_LIMIT} credits`); 56 | } else if (amount > this.balance) { 57 | onError(`Amount can't exceed account balance of ${this.balance} credits`); 58 | } else { 59 | this.balance -= amount; 60 | onSuccess(`Account balance: ${this.balance}`); 61 | } 62 | }, 63 | deposit(amount, onSuccess, onError) { 64 | if (amount > TRANSACTION_LIMIT) { 65 | onError(`Amount should not exceed ${TRANSACTION_LIMIT} credits`); 66 | } else if (amount <= 0) { 67 | onError(`Amount must be more than 0 credits`); 68 | } else { 69 | this.balance += amount; 70 | onSuccess(`Account balance: ${this.balance}`); 71 | } 72 | }, 73 | }; 74 | 75 | function handleSuccess(message) { 76 | console.log(`✅ Success! ${message}`); 77 | } 78 | function handleError(message) { 79 | console.log(`❌ Error! ${message}`); 80 | } 81 | 82 | account.withdraw(2000, handleSuccess, handleError); 83 | account.withdraw(600, handleSuccess, handleError); 84 | account.withdraw(300, handleSuccess, handleError); 85 | account.deposit(1700, handleSuccess, handleError); 86 | account.deposit(0, handleSuccess, handleError); 87 | account.deposit(-600, handleSuccess, handleError); 88 | account.deposit(600, handleSuccess, handleError); 89 | ``` 90 | 91 | ## Ejemplo 3 - Funciones CallBack 92 | 93 | Escriba una función `each(array, callback)` la cual espera un array como primer 94 | parámetro, y como segundo una función a aplicar a cada elemento del array. La 95 | función each debe devolver un nuevo array cuyos elementos son los resultados 96 | de llamar la función CallBack. 97 | 98 | ```js 99 | // Solución 100 | function each(array, callback) { 101 | const newArr = []; 102 | for (const el of array) { 103 | newArr.push(callback(el)); 104 | } 105 | return newArr; 106 | } 107 | 108 | console.log( 109 | each([64, 49, 36, 25, 16], function (value) { 110 | return value * 2; 111 | }), 112 | ); 113 | console.log( 114 | each([64, 49, 36, 25, 16], function (value) { 115 | return value - 10; 116 | }), 117 | ); 118 | console.log( 119 | each([64, 49, 36, 25, 16], function (value) { 120 | return Math.sqrt(value); 121 | }), 122 | ); 123 | console.log( 124 | each([1.5, 2.1, 16.4, 9.7, 11.3], function (value) { 125 | return Math.ceil(value); 126 | }), 127 | ); 128 | console.log( 129 | each([1.5, 2.1, 16.4, 9.7, 11.3], function (value) { 130 | return Math.floor(value); 131 | }), 132 | ); 133 | ``` 134 | 135 | ## Ejemplo 4 - Funciones de Flecha 136 | 137 | Efectúe la refactorización del código utilizando las funciones de flecha. 138 | 139 | ```js 140 | function createProduct(partialProduct, callback) { 141 | const product = { id: Date.now(), ...partialProduct }; 142 | callback(product); 143 | } 144 | 145 | function logProduct(product) { 146 | console.log(product); 147 | } 148 | 149 | function logTotalPrice(product) { 150 | console.log(product.price * product.quantity); 151 | } 152 | 153 | createProduct({ name: '🍎', price: 30, quantity: 3 }, logProduct); 154 | createProduct({ name: '🍋', price: 20, quantity: 5 }, logTotalPrice); 155 | ``` 156 | 157 | ## Ejemplo 5 - Funciones de Flecha 158 | 159 | Efectúe la refactorización del código utilizando las funciones de flecha. 160 | 161 | ```js 162 | const TRANSACTION_LIMIT = 1000; 163 | 164 | const account = { 165 | username: 'Jacob', 166 | balance: 400, 167 | withdraw(amount, onSuccess, onError) { 168 | if (amount > TRANSACTION_LIMIT) { 169 | onError(`Amount should not exceed ${TRANSACTION_LIMIT} credits`); 170 | } else if (amount > this.balance) { 171 | onError(`Amount can't exceed account balance of ${this.balance} credits`); 172 | } else { 173 | this.balance -= amount; 174 | onSuccess(`Account balance: ${this.balance}`); 175 | } 176 | }, 177 | deposit(amount, onSuccess, onError) { 178 | if (amount > TRANSACTION_LIMIT) { 179 | onError(`Amount should not exceed ${TRANSACTION_LIMIT} credits`); 180 | } else if (amount <= 0) { 181 | onError(`Amount must be more than 0 credits`); 182 | } else { 183 | this.balance += amount; 184 | onSuccess(`Account balance: ${this.balance}`); 185 | } 186 | }, 187 | }; 188 | 189 | function handleSuccess(message) { 190 | console.log(`✅ Success! ${message}`); 191 | } 192 | function handleError(message) { 193 | console.log(`❌ Error! ${message}`); 194 | } 195 | 196 | account.withdraw(2000, handleSuccess, handleError); 197 | account.withdraw(600, handleSuccess, handleError); 198 | account.withdraw(300, handleSuccess, handleError); 199 | account.deposit(1700, handleSuccess, handleError); 200 | account.deposit(0, handleSuccess, handleError); 201 | account.deposit(-600, handleSuccess, handleError); 202 | account.deposit(600, handleSuccess, handleError); 203 | ``` 204 | 205 | ## Ejemplo 6 - Funciones de Flecha en línea 206 | 207 | Efectúe la refactorización del código utilizando las funciones de flecha. 208 | 209 | ```js 210 | function each(array, callback) { 211 | const newArr = []; 212 | for (const el of array) { 213 | newArr.push(callback(el)); 214 | } 215 | return newArr; 216 | } 217 | 218 | console.log( 219 | each([64, 49, 36, 25, 16], function (value) { 220 | return value * 2; 221 | }), 222 | ); 223 | console.log( 224 | each([64, 49, 36, 25, 16], function (value) { 225 | return value - 10; 226 | }), 227 | ); 228 | console.log( 229 | each([64, 49, 36, 25, 16], function (value) { 230 | return Math.sqrt(value); 231 | }), 232 | ); 233 | console.log( 234 | each([1.5, 2.1, 16.4, 9.7, 11.3], function (value) { 235 | return Math.ceil(value); 236 | }), 237 | ); 238 | console.log( 239 | each([1.5, 2.1, 16.4, 9.7, 11.3], function (value) { 240 | return Math.floor(value); 241 | }), 242 | ); 243 | ``` 244 | 245 | ## Ejemplo 7 - Método forEach 246 | 247 | Efectúe la refactorización del código utilizando el método `forEach` y Funciones Flecha. 248 | 249 | ```js 250 | function logItems(items) { 251 | console.log(items); 252 | for (let i = 0; i < items.length; i += 1) { 253 | console.log(`${i + 1} - ${items[i]}`); 254 | } 255 | } 256 | 257 | logItems(['Mango', 'Poly', 'Ajax']); 258 | logItems(['🍎', '🍇', '🍑', '🍌', '🍋']); 259 | ``` 260 | 261 | ## Ejemplo 8 - Método forEach 262 | 263 | Efectúe la refactorización del código utilizando el método `forEach` Funciones Flecha. 264 | 265 | ```js 266 | function printContactsInfo({ names, phones }) { 267 | const nameList = names.split(','); 268 | const phoneList = phones.split(','); 269 | for (let i = 0; i < nameList.length; i += 1) { 270 | console.log(`${nameList[i]}: ${phoneList[i]}`); 271 | } 272 | } 273 | 274 | printContactsInfo({ 275 | names: 'Jacob,William,Solomon,Artemis', 276 | phones: '89001234567,89001112233,890055566377,890055566300', 277 | }); 278 | ``` 279 | 280 | ## Ejemplo 9 - Método forEach 281 | 282 | Efectúe la refactorización del código utilizando el método `forEach` Funciones Flecha. 283 | 284 | ```js 285 | function calсulateAverage(...args) { 286 | let total = 0; 287 | for (let i = 0; i < args.length; i++) { 288 | total += args[i]; 289 | } 290 | return total / args.length; 291 | } 292 | 293 | console.log(calсulateAverage(1, 2, 3, 4)); // 2.5 294 | console.log(calсulateAverage(14, 8, 2)); // 8 295 | console.log(calсulateAverage(27, 43, 2, 8, 36)); // 23.2 296 | ``` 297 | -------------------------------------------------------------------------------- /lesson-07/ru.md: -------------------------------------------------------------------------------- 1 | # Модуль 4. Занятие 7. Коллбеки. Стрелочные функции. forEach 2 | 3 | ## Example 1 - Коллбек функции 4 | 5 | Напишите следующие функции: 6 | 7 | - `createProduct(obj, callback)` - принимает объект товара без id, а также 8 | колбек. Функция создаёт обьект товара, добавляя ему уникальный идентификатор в 9 | свойство `id` и вызывает колбек передавая ему созданный обьект. 10 | - `logProduct(product)` - коллбек принимающий обьект продукта и логирующий его в 11 | консоль 12 | - `logTotalPrice(product)` - коллбек принимающий обьект продукта и логирующий 13 | общую стоимость товара в консоль 14 | 15 | ```js 16 | // Решение 17 | function createProduct(partialProduct, callback) { 18 | const product = { id: Date.now(), ...partialProduct }; 19 | callback(product); 20 | } 21 | 22 | function logProduct(product) { 23 | console.log(product); 24 | } 25 | 26 | function logTotalPrice(product) { 27 | console.log(product.price * product.quantity); 28 | } 29 | 30 | createProduct({ name: '🍎', price: 30, quantity: 3 }, logProduct); 31 | createProduct({ name: '🍋', price: 20, quantity: 5 }, logTotalPrice); 32 | ``` 33 | 34 | ## Example 2 - Коллбек функции 35 | 36 | Добавьте объекту `account` методы `withdraw(amount, onSuccess, onError)` и 37 | `deposit(amount, onSuccess, onError)`, где первый параметр это сумма операции, а 38 | второй и третий - колбеки. 39 | 40 | Метод `withdraw` вызывает onError если amount больше TRANSACTION_LIMIT или 41 | this.balance, и onSuccess в противном случае. 42 | 43 | Метод `deposit` вызывает onError если amount больше TRANSACTION_LIMIT или меньше 44 | либо равен нулю, и onSuccess в противном случае. 45 | 46 | ```js 47 | // Решение 48 | const TRANSACTION_LIMIT = 1000; 49 | 50 | const account = { 51 | username: 'Jacob', 52 | balance: 400, 53 | withdraw(amount, onSuccess, onError) { 54 | if (amount > TRANSACTION_LIMIT) { 55 | onError(`Amount should not exceed ${TRANSACTION_LIMIT} credits`); 56 | } else if (amount > this.balance) { 57 | onError(`Amount can't exceed account balance of ${this.balance} credits`); 58 | } else { 59 | this.balance -= amount; 60 | onSuccess(`Account balance: ${this.balance}`); 61 | } 62 | }, 63 | deposit(amount, onSuccess, onError) { 64 | if (amount > TRANSACTION_LIMIT) { 65 | onError(`Amount should not exceed ${TRANSACTION_LIMIT} credits`); 66 | } else if (amount <= 0) { 67 | onError(`Amount must be more than 0 credits`); 68 | } else { 69 | this.balance += amount; 70 | onSuccess(`Account balance: ${this.balance}`); 71 | } 72 | }, 73 | }; 74 | 75 | function handleSuccess(message) { 76 | console.log(`✅ Success! ${message}`); 77 | } 78 | function handleError(message) { 79 | console.log(`❌ Error! ${message}`); 80 | } 81 | 82 | account.withdraw(2000, handleSuccess, handleError); 83 | account.withdraw(600, handleSuccess, handleError); 84 | account.withdraw(300, handleSuccess, handleError); 85 | account.deposit(1700, handleSuccess, handleError); 86 | account.deposit(0, handleSuccess, handleError); 87 | account.deposit(-600, handleSuccess, handleError); 88 | account.deposit(600, handleSuccess, handleError); 89 | ``` 90 | 91 | ## Example 3 - Коллбек функции 92 | 93 | Напишите функцию `each(array, callback)`, которая первым параметром ожидает 94 | массив, а вторым - функцию, которая применится к каждому элементу массива. 95 | Функция each должна вернуть новый массив, элементами которого будут результаты 96 | вызова коллбека. 97 | 98 | ```js 99 | // Решение 100 | function each(array, callback) { 101 | const newArr = []; 102 | for (const el of array) { 103 | newArr.push(callback(el)); 104 | } 105 | return newArr; 106 | } 107 | 108 | console.log( 109 | each([64, 49, 36, 25, 16], function (value) { 110 | return value * 2; 111 | }), 112 | ); 113 | console.log( 114 | each([64, 49, 36, 25, 16], function (value) { 115 | return value - 10; 116 | }), 117 | ); 118 | console.log( 119 | each([64, 49, 36, 25, 16], function (value) { 120 | return Math.sqrt(value); 121 | }), 122 | ); 123 | console.log( 124 | each([1.5, 2.1, 16.4, 9.7, 11.3], function (value) { 125 | return Math.ceil(value); 126 | }), 127 | ); 128 | console.log( 129 | each([1.5, 2.1, 16.4, 9.7, 11.3], function (value) { 130 | return Math.floor(value); 131 | }), 132 | ); 133 | ``` 134 | 135 | ## Example 4 - Стрелочные функции 136 | 137 | Выполните рефакторинг кода используя стрелочные функции. 138 | 139 | ```js 140 | function createProduct(partialProduct, callback) { 141 | const product = { id: Date.now(), ...partialProduct }; 142 | callback(product); 143 | } 144 | 145 | function logProduct(product) { 146 | console.log(product); 147 | } 148 | 149 | function logTotalPrice(product) { 150 | console.log(product.price * product.quantity); 151 | } 152 | 153 | createProduct({ name: '🍎', price: 30, quantity: 3 }, logProduct); 154 | createProduct({ name: '🍋', price: 20, quantity: 5 }, logTotalPrice); 155 | ``` 156 | 157 | ## Example 5 - Стрелочные функции 158 | 159 | Выполните рефакторинг кода используя стрелочные функции. 160 | 161 | ```js 162 | const TRANSACTION_LIMIT = 1000; 163 | 164 | const account = { 165 | username: 'Jacob', 166 | balance: 400, 167 | withdraw(amount, onSuccess, onError) { 168 | if (amount > TRANSACTION_LIMIT) { 169 | onError(`Amount should not exceed ${TRANSACTION_LIMIT} credits`); 170 | } else if (amount > this.balance) { 171 | onError(`Amount can't exceed account balance of ${this.balance} credits`); 172 | } else { 173 | this.balance -= amount; 174 | onSuccess(`Account balance: ${this.balance}`); 175 | } 176 | }, 177 | deposit(amount, onSuccess, onError) { 178 | if (amount > TRANSACTION_LIMIT) { 179 | onError(`Amount should not exceed ${TRANSACTION_LIMIT} credits`); 180 | } else if (amount <= 0) { 181 | onError(`Amount must be more than 0 credits`); 182 | } else { 183 | this.balance += amount; 184 | onSuccess(`Account balance: ${this.balance}`); 185 | } 186 | }, 187 | }; 188 | 189 | function handleSuccess(message) { 190 | console.log(`✅ Success! ${message}`); 191 | } 192 | function handleError(message) { 193 | console.log(`❌ Error! ${message}`); 194 | } 195 | 196 | account.withdraw(2000, handleSuccess, handleError); 197 | account.withdraw(600, handleSuccess, handleError); 198 | account.withdraw(300, handleSuccess, handleError); 199 | account.deposit(1700, handleSuccess, handleError); 200 | account.deposit(0, handleSuccess, handleError); 201 | account.deposit(-600, handleSuccess, handleError); 202 | account.deposit(600, handleSuccess, handleError); 203 | ``` 204 | 205 | ## Example 6 - Инлайн стрелочные функции 206 | 207 | Выполните рефакторинг кода используя стрелочные функции. 208 | 209 | ```js 210 | function each(array, callback) { 211 | const newArr = []; 212 | for (const el of array) { 213 | newArr.push(callback(el)); 214 | } 215 | return newArr; 216 | } 217 | 218 | console.log( 219 | each([64, 49, 36, 25, 16], function (value) { 220 | return value * 2; 221 | }), 222 | ); 223 | console.log( 224 | each([64, 49, 36, 25, 16], function (value) { 225 | return value - 10; 226 | }), 227 | ); 228 | console.log( 229 | each([64, 49, 36, 25, 16], function (value) { 230 | return Math.sqrt(value); 231 | }), 232 | ); 233 | console.log( 234 | each([1.5, 2.1, 16.4, 9.7, 11.3], function (value) { 235 | return Math.ceil(value); 236 | }), 237 | ); 238 | console.log( 239 | each([1.5, 2.1, 16.4, 9.7, 11.3], function (value) { 240 | return Math.floor(value); 241 | }), 242 | ); 243 | ``` 244 | 245 | ## Example 7 - Метод forEach 246 | 247 | Выполните рефакторинг кода используя метод `forEach` и стрелочные функции. 248 | 249 | ```js 250 | function logItems(items) { 251 | console.log(items); 252 | for (let i = 0; i < items.length; i += 1) { 253 | console.log(`${i + 1} - ${items[i]}`); 254 | } 255 | } 256 | 257 | logItems(['Mango', 'Poly', 'Ajax']); 258 | logItems(['🍎', '🍇', '🍑', '🍌', '🍋']); 259 | ``` 260 | 261 | ## Example 8 - Метод forEach 262 | 263 | Выполните рефакторинг кода используя метод `forEach` и стрелочные функции. 264 | 265 | ```js 266 | function printContactsInfo({ names, phones }) { 267 | const nameList = names.split(','); 268 | const phoneList = phones.split(','); 269 | for (let i = 0; i < nameList.length; i += 1) { 270 | console.log(`${nameList[i]}: ${phoneList[i]}`); 271 | } 272 | } 273 | 274 | printContactsInfo({ 275 | names: 'Jacob,William,Solomon,Artemis', 276 | phones: '89001234567,89001112233,890055566377,890055566300', 277 | }); 278 | ``` 279 | 280 | ## Example 9 - Метод forEach 281 | 282 | Выполните рефакторинг кода используя метод `forEach` и стрелочные функции. 283 | 284 | ```js 285 | function calсulateAverage(...args) { 286 | let total = 0; 287 | for (let i = 0; i < args.length; i++) { 288 | total += args[i]; 289 | } 290 | return total / args.length; 291 | } 292 | 293 | console.log(calсulateAverage(1, 2, 3, 4)); // 2.5 294 | console.log(calсulateAverage(14, 8, 2)); // 8 295 | console.log(calсulateAverage(27, 43, 2, 8, 36)); // 23.2 296 | ``` 297 | -------------------------------------------------------------------------------- /lesson-07/uk.md: -------------------------------------------------------------------------------- 1 | # Модуль 4. Заняття 7. Коллбеки. Стрілочні функції. forEach 2 | 3 | ## Example 1 - Коллбек функції 4 | 5 | Напишіть наступні функції: 6 | 7 | - `createProduct(obj, callback)` - приймає об'єкт товару без id, а також 8 | коллбек. Функція створює об'єкт товару, додаючи йому унікальний ідентифікатор у 9 | властивість `id` та викликає коллбек передаючи йому створений об'єкт. 10 | - `logProduct(product)` - колббек приймаючий об'єкт продукту і логуючий його в 11 | консоль 12 | - `logTotalPrice(product)` - колббек, що приймає об'єкт продукту і логіює загальну 13 | вартість товару в консоль 14 | 15 | ```js 16 | // Рішення 17 | function createProduct(partialProduct, callback) { 18 | const product = { id: Date.now(), ...partialProduct }; 19 | callback(product); 20 | } 21 | 22 | function logProduct(product) { 23 | console.log(product); 24 | } 25 | 26 | function logTotalPrice(product) { 27 | console.log(product.price * product.quantity); 28 | } 29 | 30 | createProduct({ name: '🍎', price: 30, quantity: 3 }, logProduct); 31 | createProduct({ name: '🍋', price: 20, quantity: 5 }, logTotalPrice); 32 | ``` 33 | 34 | ## Example 2 - Коллбек функції 35 | 36 | Додайте об'єкт `account` методи `withdraw(amount, onSuccess, onError)` та 37 | `deposit(amount, onSuccess, onError)`, де перший параметр це сума операції, а 38 | другий та третій - коллбеки. 39 | 40 | Метод `withdraw` викликає onError якщо amount більше TRANSACTION_LIMIT або 41 | this.balance, і onSuccess в іншому випадку. 42 | 43 | Метод `deposit` викликає onError якщо amount більше TRANSACTION_LIMIT або менше 44 | або дорівнює нулю, і onSuccess в іншому випадку. 45 | 46 | ```js 47 | // Рішення 48 | const TRANSACTION_LIMIT = 1000; 49 | 50 | const account = { 51 | username: 'Jacob', 52 | balance: 400, 53 | withdraw(amount, onSuccess, onError) { 54 | if (amount > TRANSACTION_LIMIT) { 55 | onError(`Amount should not exceed ${TRANSACTION_LIMIT} credits`); 56 | } else if (amount > this.balance) { 57 | onError(`Amount can't exceed account balance of ${this.balance} credits`); 58 | } else { 59 | this.balance -= amount; 60 | onSuccess(`Account balance: ${this.balance}`); 61 | } 62 | }, 63 | deposit(amount, onSuccess, onError) { 64 | if (amount > TRANSACTION_LIMIT) { 65 | onError(`Amount should not exceed ${TRANSACTION_LIMIT} credits`); 66 | } else if (amount <= 0) { 67 | onError(`Amount must be more than 0 credits`); 68 | } else { 69 | this.balance += amount; 70 | onSuccess(`Account balance: ${this.balance}`); 71 | } 72 | }, 73 | }; 74 | 75 | function handleSuccess(message) { 76 | console.log(`✅ Success! ${message}`); 77 | } 78 | function handleError(message) { 79 | console.log(`❌ Error! ${message}`); 80 | } 81 | 82 | account.withdraw(2000, handleSuccess, handleError); 83 | account.withdraw(600, handleSuccess, handleError); 84 | account.withdraw(300, handleSuccess, handleError); 85 | account.deposit(1700, handleSuccess, handleError); 86 | account.deposit(0, handleSuccess, handleError); 87 | account.deposit(-600, handleSuccess, handleError); 88 | account.deposit(600, handleSuccess, handleError); 89 | ``` 90 | 91 | ## Example 3 - Коллбек функції 92 | 93 | Напишіть функцію `each(array, callback)`, яка першим параметром очікує 94 | масив, а другим - функцію, яка застосовується до кожного елемента масиву. 95 | Функція each повинна повернути новий масив, елементами якого будуть результати 96 | виклику коллбека. 97 | 98 | ```js 99 | // Рішення 100 | function each(array, callback) { 101 | const newArr = []; 102 | for (const el of array) { 103 | newArr.push(callback(el)); 104 | } 105 | return newArr; 106 | } 107 | 108 | console.log( 109 | each([64, 49, 36, 25, 16], function (value) { 110 | return value * 2; 111 | }), 112 | ); 113 | console.log( 114 | each([64, 49, 36, 25, 16], function (value) { 115 | return value - 10; 116 | }), 117 | ); 118 | console.log( 119 | each([64, 49, 36, 25, 16], function (value) { 120 | return Math.sqrt(value); 121 | }), 122 | ); 123 | console.log( 124 | each([1.5, 2.1, 16.4, 9.7, 11.3], function (value) { 125 | return Math.ceil(value); 126 | }), 127 | ); 128 | console.log( 129 | each([1.5, 2.1, 16.4, 9.7, 11.3], function (value) { 130 | return Math.floor(value); 131 | }), 132 | ); 133 | ``` 134 | 135 | ## Example 4 - Стрілочні функції 136 | 137 | Виконайте рефакторинг коду за допомогою стрілочних функцій. 138 | 139 | ```js 140 | function createProduct(partialProduct, callback) { 141 | const product = { id: Date.now(), ...partialProduct }; 142 | callback(product); 143 | } 144 | 145 | function logProduct(product) { 146 | console.log(product); 147 | } 148 | 149 | function logTotalPrice(product) { 150 | console.log(product.price * product.quantity); 151 | } 152 | 153 | createProduct({ name: '🍎', price: 30, quantity: 3 }, logProduct); 154 | createProduct({ name: '🍋', price: 20, quantity: 5 }, logTotalPrice); 155 | ``` 156 | 157 | ## Example 5 - Стрілочні функції 158 | 159 | Виконайте рефакторинг коду за допомогою стрілочних функцій. 160 | 161 | ```js 162 | const TRANSACTION_LIMIT = 1000; 163 | 164 | const account = { 165 | username: 'Jacob', 166 | balance: 400, 167 | withdraw(amount, onSuccess, onError) { 168 | if (amount > TRANSACTION_LIMIT) { 169 | onError(`Amount should not exceed ${TRANSACTION_LIMIT} credits`); 170 | } else if (amount > this.balance) { 171 | onError(`Amount can't exceed account balance of ${this.balance} credits`); 172 | } else { 173 | this.balance -= amount; 174 | onSuccess(`Account balance: ${this.balance}`); 175 | } 176 | }, 177 | deposit(amount, onSuccess, onError) { 178 | if (amount > TRANSACTION_LIMIT) { 179 | onError(`Amount should not exceed ${TRANSACTION_LIMIT} credits`); 180 | } else if (amount <= 0) { 181 | onError(`Amount must be more than 0 credits`); 182 | } else { 183 | this.balance += amount; 184 | onSuccess(`Account balance: ${this.balance}`); 185 | } 186 | }, 187 | }; 188 | 189 | function handleSuccess(message) { 190 | console.log(`✅ Success! ${message}`); 191 | } 192 | function handleError(message) { 193 | console.log(`❌ Error! ${message}`); 194 | } 195 | 196 | account.withdraw(2000, handleSuccess, handleError); 197 | account.withdraw(600, handleSuccess, handleError); 198 | account.withdraw(300, handleSuccess, handleError); 199 | account.deposit(1700, handleSuccess, handleError); 200 | account.deposit(0, handleSuccess, handleError); 201 | account.deposit(-600, handleSuccess, handleError); 202 | account.deposit(600, handleSuccess, handleError); 203 | ``` 204 | 205 | ## Example 6 - Інлайн стрілочні функції 206 | 207 | Виконайте рефакторинг коду за допомогою стрілочних функцій. 208 | 209 | ```js 210 | function each(array, callback) { 211 | const newArr = []; 212 | for (const el of array) { 213 | newArr.push(callback(el)); 214 | } 215 | return newArr; 216 | } 217 | 218 | console.log( 219 | each([64, 49, 36, 25, 16], function (value) { 220 | return value * 2; 221 | }), 222 | ); 223 | console.log( 224 | each([64, 49, 36, 25, 16], function (value) { 225 | return value - 10; 226 | }), 227 | ); 228 | console.log( 229 | each([64, 49, 36, 25, 16], function (value) { 230 | return Math.sqrt(value); 231 | }), 232 | ); 233 | console.log( 234 | each([1.5, 2.1, 16.4, 9.7, 11.3], function (value) { 235 | return Math.ceil(value); 236 | }), 237 | ); 238 | console.log( 239 | each([1.5, 2.1, 16.4, 9.7, 11.3], function (value) { 240 | return Math.floor(value); 241 | }), 242 | ); 243 | ``` 244 | 245 | ## Example 7 - Метод forEach 246 | 247 | Виконайте рефакторинг коду за допомогою методу `forEach` та стрілочні функції. 248 | 249 | ```js 250 | function logItems(items) { 251 | console.log(items); 252 | for (let i = 0; i < items.length; i += 1) { 253 | console.log(`${i + 1} - ${items[i]}`); 254 | } 255 | } 256 | 257 | logItems(['Mango', 'Poly', 'Ajax']); 258 | logItems(['🍎', '🍇', '🍑', '🍌', '🍋']); 259 | ``` 260 | 261 | ## Example 8 - Метод forEach 262 | 263 | Виконайте рефакторинг коду за допомогою методу `forEach` та стрілочні функції. 264 | 265 | ```js 266 | function printContactsInfo({ names, phones }) { 267 | const nameList = names.split(','); 268 | const phoneList = phones.split(','); 269 | for (let i = 0; i < nameList.length; i += 1) { 270 | console.log(`${nameList[i]}: ${phoneList[i]}`); 271 | } 272 | } 273 | 274 | printContactsInfo({ 275 | names: 'Jacob,William,Solomon,Artemis', 276 | phones: '89001234567,89001112233,890055566377,890055566300', 277 | }); 278 | ``` 279 | 280 | ## Example 9 - Метод forEach 281 | 282 | Виконайте рефакторинг коду за допомогою методу `forEach` та стрілочні функції. 283 | 284 | ```js 285 | function calсulateAverage(...args) { 286 | let total = 0; 287 | for (let i = 0; i < args.length; i++) { 288 | total += args[i]; 289 | } 290 | return total / args.length; 291 | } 292 | 293 | console.log(calсulateAverage(1, 2, 3, 4)); // 2.5 294 | console.log(calсulateAverage(14, 8, 2)); // 8 295 | console.log(calсulateAverage(27, 43, 2, 8, 36)); // 23.2 296 | ``` 297 | -------------------------------------------------------------------------------- /lesson-08/en.md: -------------------------------------------------------------------------------- 1 | # Module 4 - Lesson 8 - Iterating Array Methods 2 | 3 | ## Collection of objects for all examples with cars 4 | 5 | ```js 6 | const cars = [ 7 | { make: 'Honda', model: 'CR-V', type: 'suv', amount: 14, price: 24045, onSale: true }, 8 | { make: 'Honda', model: 'Accord', type: 'sedan', amount: 2, price: 22455, onSale: true }, 9 | { make: 'Mazda', model: 'Mazda 6', type: 'sedan', amount: 8, price: 24195, onSale: false }, 10 | { make: 'Mazda', model: 'CX-9', type: 'suv', amount: 7, price: 31520, onSale: true }, 11 | { make: 'Toyota', model: '4Runner', type: 'suv', amount: 19, price: 34210, onSale: false }, 12 | { make: 'Toyota', model: 'Sequoia', type: 'suv', amount: 16, price: 45560, onSale: false }, 13 | { make: 'Toyota', model: 'Tacoma', type: 'truck', amount: 4, price: 24320, onSale: true }, 14 | { make: 'Ford', model: 'F-150', type: 'truck', amount: 11, price: 27110, onSale: true }, 15 | { make: 'Ford', model: 'Fusion', type: 'sedan', amount: 13, price: 22120, onSale: true }, 16 | { make: 'Ford', model: 'Explorer', type: 'suv', amount: 6, price: 31660, onSale: false } 17 | ]; 18 | ``` 19 | 20 | ## Example 1 - Map method 21 | 22 | Let the `getModels` function return an array of models (model field) of all 23 | cars. 24 | 25 | ```js 26 | const getModels = cars => {}; 27 | 28 | console.table(getModels(cars)); 29 | ``` 30 | 31 | ## Example 2 - Map method 32 | 33 | Let the `makeCarsWithDiscount` function return a new array of objects with a changed 34 | value of the `price` property depending on the discount passed. 35 | 36 | ```js 37 | const makeCarsWithDiscount = (cars, discount) => {}; 38 | 39 | console.table(makeCarsWithDiscount(cars, 0.2)); 40 | console.table(makeCarsWithDiscount(cars, 0.4)); 41 | ``` 42 | 43 | ## Example 3 -Filter method 44 | 45 | Let the `filterByPrice` function return an array of cars whose price is less 46 | than the value of the `threshold` parameter. 47 | 48 | ```js 49 | const filterByPrice = (cars, threshold) => {}; 50 | 51 | console.table(filterByPrice(cars, 30000)); 52 | console.table(filterByPrice(cars, 25000)); 53 | ``` 54 | 55 | ## Example 4 - Filter method 56 | 57 | Let the `getCarsWithDiscount` function return an array of cars whose 58 | onSale property is true. 59 | 60 | ```js 61 | const getCarsWithDiscount = cars => {}; 62 | 63 | console.table(getCarsWithDiscount(cars)); 64 | ``` 65 | 66 | ## Example 5 - Filter method 67 | 68 | Let the `getCarsWithType` function return an array of cars whose type 69 | coincide with the value of the `type` parameter. 70 | 71 | ```js 72 | const getCarsWithType = (cars, type) => {}; 73 | 74 | console.table(getCarsWithType(cars, 'suv')); 75 | console.table(getCarsWithType(cars, 'sedan')); 76 | ``` 77 | 78 | ## Example 6 - The find method 79 | 80 | ```js 81 | const getCarByModel = (cars, model) => {}; 82 | 83 | console.log(getCarByModel(cars, 'F-150')); 84 | console.log(getCarByModel(cars, 'CX-9')); 85 | ``` 86 | 87 | ## Example 7 - Sort method 88 | 89 | Let the `sortByAscendingAmount` function return a new array of cars 90 | sorted in ascending order by the value of the `amount` property. 91 | 92 | ```js 93 | const sortByAscendingAmount = cars => {}; 94 | 95 | console.table(sortByAscendingAmount(cars)); 96 | ``` 97 | 98 | ## Example 8 - Sort method 99 | 100 | Let the `sortByDescendingPrice` function return a new array of cars 101 | sorted in descending order by the value of the `price` property. 102 | 103 | ```js 104 | const sortByDescendingPrice = cars => {}; 105 | 106 | console.table(sortByDescendingPrice(cars)); 107 | ``` 108 | 109 | ## Example 9 - Sort method 110 | 111 | Let the `sortByModel` function return a new array of cars sorted 112 | by model name in alphabetical and reverse alphabetical order, depending on 113 | the value of the `order` parameter. 114 | 115 | ```js 116 | const sortByModel = (cars, order) => {}; 117 | 118 | console.table(sortByModel(cars, 'asc')); 119 | console.table(sortByModel(cars, 'desc')); 120 | ``` 121 | 122 | ## Example 10 - Reduce method 123 | 124 | Let the `getTotalAmount` function return the total number of cars (the value 125 | of the `amount` properties). 126 | 127 | ```js 128 | const getTotalAmount = cars => {}; 129 | 130 | console.log(getTotalAmount(cars)); 131 | ``` 132 | 133 | ## Example 11 - Method chains 134 | 135 | Let the `getAvailableCarNames` function return an array of car models, but 136 | only those that are currently for sale. 137 | 138 | ```js 139 | const getModelsOnSale = cars => {}; 140 | 141 | console.table(getModelsOnSale(cars)); 142 | ``` 143 | 144 | ## Example 12 - Method chains 145 | 146 | 147 | Let the `getSortedCarsOnSale` function return an array of cars for sale 148 | (onSale property), sorted by price ascending. 149 | 150 | ```js 151 | const getSortedCarsOnSale = cars => {}; 152 | 153 | console.table(getSortedCarsOnSale(cars)); 154 | ``` 155 | -------------------------------------------------------------------------------- /lesson-08/es.md: -------------------------------------------------------------------------------- 1 | # Módulo 4. Clase 8. Métodos de indexación de Arrays 2 | 3 | ## La colección de objetos para todos los ejemplos que tengan coches 4 | 5 | ```js 6 | const cars = [ 7 | { make: 'Honda', model: 'CR-V', type: 'suv', amount: 14, price: 24045, onSale: true }, 8 | { make: 'Honda', model: 'Accord', type: 'sedan', amount: 2, price: 22455, onSale: true }, 9 | { make: 'Mazda', model: 'Mazda 6', type: 'sedan', amount: 8, price: 24195, onSale: false }, 10 | { make: 'Mazda', model: 'CX-9', type: 'suv', amount: 7, price: 31520, onSale: true }, 11 | { make: 'Toyota', model: '4Runner', type: 'suv', amount: 19, price: 34210, onSale: false }, 12 | { make: 'Toyota', model: 'Sequoia', type: 'suv', amount: 16, price: 45560, onSale: false }, 13 | { make: 'Toyota', model: 'Tacoma', type: 'truck', amount: 4, price: 24320, onSale: true }, 14 | { make: 'Ford', model: 'F-150', type: 'truck', amount: 11, price: 27110, onSale: true }, 15 | { make: 'Ford', model: 'Fusion', type: 'sedan', amount: 13, price: 22120, onSale: true }, 16 | { make: 'Ford', model: 'Explorer', type: 'suv', amount: 6, price: 31660, onSale: false } 17 | ]; 18 | ``` 19 | 20 | ## Ejemplo 1 - Método map 21 | 22 | Haz que la función `getModels` devuelva un array de modelos (campo model) 23 | de todos los coches. 24 | 25 | ```js 26 | const getModels = cars => {}; 27 | 28 | console.table(getModels(cars)); 29 | ``` 30 | 31 | ## Ejemplo 2 - Método map 32 | 33 | Haz que la función `makeCarsWithDiscount` devuelva un nuevo array de objetos 34 | con el valor de la propiedad `price` modificado, en función del descuento introducido. 35 | 36 | ```js 37 | const makeCarsWithDiscount = (cars, discount) => {}; 38 | 39 | console.table(makeCarsWithDiscount(cars, 0.2)); 40 | console.table(makeCarsWithDiscount(cars, 0.4)); 41 | ``` 42 | 43 | ## Ejemplo 3 - Método filter 44 | 45 | Que la función `filterByPrice` devuelva un array de coches cuyo precio 46 | sea inferior al valor del parámetro `threshold`. 47 | 48 | ```js 49 | const filterByPrice = (cars, threshold) => {}; 50 | 51 | console.table(filterByPrice(cars, 30000)); 52 | console.table(filterByPrice(cars, 25000)); 53 | ``` 54 | 55 | ## Ejemplo 4 - Método filter 56 | 57 | Haz que la función `getCarsWithDiscount` devuelva un array de coches, cuya 58 | propiedad onSale sea true. 59 | 60 | ```js 61 | const getCarsWithDiscount = cars => {}; 62 | 63 | console.table(getCarsWithDiscount(cars)); 64 | ``` 65 | 66 | ## Ejemplo 5 - Método filter 67 | 68 | Haz que la función `getCarsWithType` devuelva un array de coches 69 | cuyo tipo coincida con el valor del parámetro `type`. 70 | 71 | ```js 72 | const getCarsWithType = (cars, type) => {}; 73 | 74 | console.table(getCarsWithType(cars, 'suv')); 75 | console.table(getCarsWithType(cars, 'sedan')); 76 | ``` 77 | 78 | ## Ejemplo 6 - Método find 79 | 80 | ```js 81 | const getCarByModel = (cars, model) => {}; 82 | 83 | console.log(getCarByModel(cars, 'F-150')); 84 | console.log(getCarByModel(cars, 'CX-9')); 85 | ``` 86 | 87 | ## Ejemplo 7 - Método sort 88 | 89 | Haz que la función `sortByAscendingAmount` devuelva un nuevo array de coches 90 | ordenados de forma ascendente según el valor de la propiedad `amount`. 91 | 92 | ```js 93 | const sortByAscendingAmount = cars => {}; 94 | 95 | console.table(sortByAscendingAmount(cars)); 96 | ``` 97 | 98 | ## Ejemplo 8 - Método sort 99 | 100 | Haz que la función `sortByDescendingPrice` devuelva un nuevo array de coches 101 | ordenados de forma descendente según el valor de la propiedad `price`. 102 | 103 | ```js 104 | const sortByDescendingPrice = cars => {}; 105 | 106 | console.table(sortByDescendingPrice(cars)); 107 | ``` 108 | 109 | ## Ejemplo 9 - Método sort 110 | 111 | Haz que la función `sortByModel` devuelva un nuevo array de coches ordenados por 112 | nombre de modelo en orden alfabético y alfabético invertido, dependiendo 113 | del valor del parámetro `order`. 114 | 115 | ```js 116 | const sortByModel = (cars, order) => {}; 117 | 118 | console.table(sortByModel(cars, 'asc')); 119 | console.table(sortByModel(cars, 'desc')); 120 | ``` 121 | 122 | ## Ejemplo 10 - Método reduce 123 | 124 | Haz que la función `getTotalAmount` devuelva el número total 125 | de coches (valor de propiedades `amount`). 126 | 127 | ```js 128 | const getTotalAmount = cars => {}; 129 | 130 | console.log(getTotalAmount(cars)); 131 | ``` 132 | 133 | ## Ejemplo 11 - Cadenas de métodos 134 | 135 | Haz que la función `getAvailableCarNames` devuelva un array de modelos de 136 | coches, pero sólo los que están rebajados actualmente. 137 | 138 | ```js 139 | const getModelsOnSale = cars => {}; 140 | 141 | console.table(getModelsOnSale(cars)); 142 | ``` 143 | 144 | ## Ejemplo 12 - Cadenas de métodos 145 | 146 | Haz que la función `getSortedCarsOnSale` devuelva un array de coches 147 | en oferta (propiedad onSale) ordenados por precio ascendente. 148 | 149 | ```js 150 | const getSortedCarsOnSale = cars => {}; 151 | 152 | console.table(getSortedCarsOnSale(cars)); 153 | ``` 154 | -------------------------------------------------------------------------------- /lesson-08/ru.md: -------------------------------------------------------------------------------- 1 | # Модуль 4. Занятие 8. Перебирающие методы массива 2 | 3 | ## Коллекция объектов для всех примеров с автомобилями 4 | 5 | ```js 6 | const cars = [ 7 | { make: 'Honda', model: 'CR-V', type: 'suv', amount: 14, price: 24045, onSale: true }, 8 | { make: 'Honda', model: 'Accord', type: 'sedan', amount: 2, price: 22455, onSale: true }, 9 | { make: 'Mazda', model: 'Mazda 6', type: 'sedan', amount: 8, price: 24195, onSale: false }, 10 | { make: 'Mazda', model: 'CX-9', type: 'suv', amount: 7, price: 31520, onSale: true }, 11 | { make: 'Toyota', model: '4Runner', type: 'suv', amount: 19, price: 34210, onSale: false }, 12 | { make: 'Toyota', model: 'Sequoia', type: 'suv', amount: 16, price: 45560, onSale: false }, 13 | { make: 'Toyota', model: 'Tacoma', type: 'truck', amount: 4, price: 24320, onSale: true }, 14 | { make: 'Ford', model: 'F-150', type: 'truck', amount: 11, price: 27110, onSale: true }, 15 | { make: 'Ford', model: 'Fusion', type: 'sedan', amount: 13, price: 22120, onSale: true }, 16 | { make: 'Ford', model: 'Explorer', type: 'suv', amount: 6, price: 31660, onSale: false } 17 | ]; 18 | ``` 19 | 20 | ## Example 1 - Метод map 21 | 22 | Пусть функция `getModels` возвращает массив моделей (поле model) всех 23 | автомобилей. 24 | 25 | ```js 26 | const getModels = cars => {}; 27 | 28 | console.table(getModels(cars)); 29 | ``` 30 | 31 | ## Example 2 - Метод map 32 | 33 | Пусть функция `makeCarsWithDiscount` возвращает новый массив объектов с изменным 34 | значением свойства `price` в зависимости от переданной скидки. 35 | 36 | ```js 37 | const makeCarsWithDiscount = (cars, discount) => {}; 38 | 39 | console.table(makeCarsWithDiscount(cars, 0.2)); 40 | console.table(makeCarsWithDiscount(cars, 0.4)); 41 | ``` 42 | 43 | ## Example 3 - Метод filter 44 | 45 | Пусть функция `filterByPrice` возвращает массив автомобилей цена которых меньше 46 | чем значение параметра `threshold`. 47 | 48 | ```js 49 | const filterByPrice = (cars, threshold) => {}; 50 | 51 | console.table(filterByPrice(cars, 30000)); 52 | console.table(filterByPrice(cars, 25000)); 53 | ``` 54 | 55 | ## Example 4 - Метод filter 56 | 57 | Пусть функция `getCarsWithDiscount` возвращает массив автомобилей свойство 58 | onSale которых true. 59 | 60 | ```js 61 | const getCarsWithDiscount = cars => {}; 62 | 63 | console.table(getCarsWithDiscount(cars)); 64 | ``` 65 | 66 | ## Example 5 - Метод filter 67 | 68 | Пусть функция `getCarsWithType` возвращает массив автомобилей тип которых 69 | совпадает со значением параметра `type`. 70 | 71 | ```js 72 | const getCarsWithType = (cars, type) => {}; 73 | 74 | console.table(getCarsWithType(cars, 'suv')); 75 | console.table(getCarsWithType(cars, 'sedan')); 76 | ``` 77 | 78 | ## Example 6 - Метод find 79 | 80 | ```js 81 | const getCarByModel = (cars, model) => {}; 82 | 83 | console.log(getCarByModel(cars, 'F-150')); 84 | console.log(getCarByModel(cars, 'CX-9')); 85 | ``` 86 | 87 | ## Example 7 - Метод sort 88 | 89 | Пусть функция `sortByAscendingAmount` возвращает новый массив автомобилей 90 | отсортированный по возврастанию значения свойства `amount`. 91 | 92 | ```js 93 | const sortByAscendingAmount = cars => {}; 94 | 95 | console.table(sortByAscendingAmount(cars)); 96 | ``` 97 | 98 | ## Example 8 - Метод sort 99 | 100 | Пусть функция `sortByDescendingPrice` возвращает новый массив автомобилей 101 | отсортированный по убыванию значения свойства `price`. 102 | 103 | ```js 104 | const sortByDescendingPrice = cars => {}; 105 | 106 | console.table(sortByDescendingPrice(cars)); 107 | ``` 108 | 109 | ## Example 9 - Метод sort 110 | 111 | Пусть функция `sortByModel` возвращает новый массив автомобилей отсортированный 112 | по названию модели в алфавитном и обратном алфавитном порядке, в засисимости от 113 | значения параметра `order`. 114 | 115 | ```js 116 | const sortByModel = (cars, order) => {}; 117 | 118 | console.table(sortByModel(cars, 'asc')); 119 | console.table(sortByModel(cars, 'desc')); 120 | ``` 121 | 122 | ## Example 10 - Метод reduce 123 | 124 | Пусть функция `getTotalAmount` возвращает общее количество автомобилей(значение 125 | свойств `amount`). 126 | 127 | ```js 128 | const getTotalAmount = cars => {}; 129 | 130 | console.log(getTotalAmount(cars)); 131 | ``` 132 | 133 | ## Example 11 - Цепочки методов 134 | 135 | Пусть функция `getAvailableCarNames` возвращает массив моделей автомобилей, но 136 | только тех, которые сейчас на распродаже. 137 | 138 | ```js 139 | const getModelsOnSale = cars => {}; 140 | 141 | console.table(getModelsOnSale(cars)); 142 | ``` 143 | 144 | ## Example 12 - Цепочки методов 145 | 146 | Пусть функция `getSortedCarsOnSale` возвращает массив автомобилей на распродаже 147 | (свойство onSale), отсортированных по возрастанию цены. 148 | 149 | ```js 150 | const getSortedCarsOnSale = cars => {}; 151 | 152 | console.table(getSortedCarsOnSale(cars)); 153 | ``` 154 | -------------------------------------------------------------------------------- /lesson-08/uk.md: -------------------------------------------------------------------------------- 1 | # Модуль 4. Заняття 8. Перебираючі методи масиву 2 | 3 | ## Колекція об'єктів для всіх прикладів з автомобілями 4 | 5 | ```js 6 | const cars = [ 7 | { make: 'Honda', model: 'CR-V', type: 'suv', amount: 14, price: 24045, onSale: true }, 8 | { make: 'Honda', model: 'Accord', type: 'sedan', amount: 2, price: 22455, onSale: true }, 9 | { make: 'Mazda', model: 'Mazda 6', type: 'sedan', amount: 8, price: 24195, onSale: false }, 10 | { make: 'Mazda', model: 'CX-9', type: 'suv', amount: 7, price: 31520, onSale: true }, 11 | { make: 'Toyota', model: '4Runner', type: 'suv', amount: 19, price: 34210, onSale: false }, 12 | { make: 'Toyota', model: 'Sequoia', type: 'suv', amount: 16, price: 45560, onSale: false }, 13 | { make: 'Toyota', model: 'Tacoma', type: 'truck', amount: 4, price: 24320, onSale: true }, 14 | { make: 'Ford', model: 'F-150', type: 'truck', amount: 11, price: 27110, onSale: true }, 15 | { make: 'Ford', model: 'Fusion', type: 'sedan', amount: 13, price: 22120, onSale: true }, 16 | { make: 'Ford', model: 'Explorer', type: 'suv', amount: 6, price: 31660, onSale: false } 17 | ]; 18 | ``` 19 | 20 | ## Example 1 - Метод map 21 | 22 | Нехай функція `getModels` повертає масив моделей (поле model) всіх 23 | автомобілів. 24 | 25 | ```js 26 | const getModels = cars => {}; 27 | 28 | console.table(getModels(cars)); 29 | ``` 30 | 31 | ## Example 2 - Метод map 32 | 33 | Нехай функція `makeCarsWithDiscount` повертає новий масив об'єктів із змінним 34 | значенням властивості `price` залежно від переданої знижки. 35 | 36 | ```js 37 | const makeCarsWithDiscount = (cars, discount) => {}; 38 | 39 | console.table(makeCarsWithDiscount(cars, 0.2)); 40 | console.table(makeCarsWithDiscount(cars, 0.4)); 41 | ``` 42 | 43 | ## Example 3 - Метод filter 44 | 45 | Нехай функція `filterByPrice` повертає масив автомобілів ціна яких менша 46 | ніж значення параметра `threshold`. 47 | 48 | ```js 49 | const filterByPrice = (cars, threshold) => {}; 50 | 51 | console.table(filterByPrice(cars, 30000)); 52 | console.table(filterByPrice(cars, 25000)); 53 | ``` 54 | 55 | ## Example 4 - Метод filter 56 | 57 | Нехай функція `getCarsWithDiscount` повертає масив автомобілів властивість 58 | onSale яких true. 59 | 60 | ```js 61 | const getCarsWithDiscount = cars => {}; 62 | 63 | console.table(getCarsWithDiscount(cars)); 64 | ``` 65 | 66 | ## Example 5 - Метод filter 67 | 68 | Нехай функція `getCarsWithType` повертає масив автомобілів тип яких 69 | збігається зі значенням параметра `type`. 70 | 71 | ```js 72 | const getCarsWithType = (cars, type) => {}; 73 | 74 | console.table(getCarsWithType(cars, 'suv')); 75 | console.table(getCarsWithType(cars, 'sedan')); 76 | ``` 77 | 78 | ## Example 6 - Метод find 79 | 80 | ```js 81 | const getCarByModel = (cars, model) => {}; 82 | 83 | console.log(getCarByModel(cars, 'F-150')); 84 | console.log(getCarByModel(cars, 'CX-9')); 85 | ``` 86 | 87 | ## Example 7 - Метод sort 88 | 89 | Нехай функція `sortByAscendingAmount` повертає новий масив автомобілів відсортований за 90 | зростанням значення якості `amount`. 91 | 92 | ```js 93 | const sortByAscendingAmount = cars => {}; 94 | 95 | console.table(sortByAscendingAmount(cars)); 96 | ``` 97 | 98 | ## Example 8 - Метод sort 99 | 100 | Нехай функція `sortByDescendingPrice` повертає новий масив автомобілів 101 | відсортований за зменшенням значення властивості `price`. 102 | 103 | ```js 104 | const sortByDescendingPrice = cars => {}; 105 | 106 | console.table(sortByDescendingPrice(cars)); 107 | ``` 108 | 109 | ## Example 9 - Метод sort 110 | 111 | Нехай функція `sortByModel` повертає новий масив автомобілів відсортований 112 | за назвою моделі в алфавітному та зворотному алфавітному порядку, в залежності від 113 | значення параметра `order`. 114 | 115 | ```js 116 | const sortByModel = (cars, order) => {}; 117 | 118 | console.table(sortByModel(cars, 'asc')); 119 | console.table(sortByModel(cars, 'desc')); 120 | ``` 121 | 122 | ## Example 10 - Метод reduce 123 | 124 | Нехай функція `getTotalAmount` повертає загальну кількість автомобілів (значення 125 | властивостей `amount`). 126 | 127 | ```js 128 | const getTotalAmount = cars => {}; 129 | 130 | console.log(getTotalAmount(cars)); 131 | ``` 132 | 133 | ## Example 11 - Ланцюжки методів 134 | 135 | Нехай функція `getAvailableCarNames` повертає масив моделей автомобілів, але 136 | тільки тих, які зараз на розпродажі. 137 | 138 | ```js 139 | const getModelsOnSale = cars => {}; 140 | 141 | console.table(getModelsOnSale(cars)); 142 | ``` 143 | 144 | ## Example 12 - Ланцюжки методів 145 | 146 | Нехай функція `getSortedCarsOnSale` повертає масив автомобілів на розпродажі 147 | (Властивість onSale), відсортованих за зростанням ціни. 148 | 149 | ```js 150 | const getSortedCarsOnSale = cars => {}; 151 | 152 | console.table(getSortedCarsOnSale(cars)); 153 | ``` 154 | -------------------------------------------------------------------------------- /lesson-09/en.md: -------------------------------------------------------------------------------- 1 | # Module 5 - Lesson 9 - Function call context and this 2 | 3 | ## Example 1 - Jewelry workshop 4 | 5 | Write a `calcTotalPrice(stoneName)` method that takes the name of a stone, 6 | calculates and returns the total cost of stones with that name, price, and 7 | quantity from the `stones` property. 8 | 9 | ```js 10 | const chopShop = { 11 | stones: [ 12 | { name: 'Emerald', price: 1300, quantity: 4 }, 13 | { name: 'Diamond', price: 2700, quantity: 3 }, 14 | { name: 'Sapphire', price: 1400, quantity: 7 }, 15 | { name: 'Ruby', price: 800, quantity: 2 }, 16 | ], 17 | calcTotalPrice(stoneName) {}, 18 | }; 19 | 20 | console.log(chopShop.calcTotalPrice('Emerald')); // 5200 21 | console.log(chopShop.calcTotalPrice('Diamond')); // 8100 22 | console.log(chopShop.calcTotalPrice('Sapphire')); // 9800 23 | console.log(chopShop.calcTotalPrice('Ruby')); // 1600 24 | ``` 25 | 26 | ## Example 2 - Phone book 27 | 28 | Make methods' refactoring of the `phonebook` object to make the code work. 29 | 30 | ```js 31 | const phonebook = { 32 | contacts: [], 33 | add(contact) { 34 | const newContact = { 35 | list: 'default', 36 | ...contact, 37 | id: generateId(), 38 | createdAt: getDate(), 39 | }; 40 | contacts.push(newContact); 41 | }, 42 | generateId() { 43 | return '_' + Math.random().toString(36).substr(2, 9); 44 | }, 45 | getDate() { 46 | return Date.now(); 47 | }, 48 | }; 49 | 50 | console.log( 51 | phonebook.add({ 52 | name: 'Mango', 53 | email: 'mango@mail.com', 54 | list: 'friends', 55 | }), 56 | ); 57 | console.log( 58 | phonebook.add({ 59 | name: 'Poly', 60 | email: 'poly@hotmail.com', 61 | }), 62 | ); 63 | ``` 64 | 65 | ## Example 3 -Calculator 66 | 67 | Create a `calculator` object with three methods: 68 | 69 | - `read(a, b)`- takes two values and stores them as object properties. 70 | - `add()` - returns the sum of the stored values. 71 | - `mult()` - multiplies the stored values and returns the result. 72 | 73 | ```js 74 | const calculator = {}; 75 | ``` 76 | -------------------------------------------------------------------------------- /lesson-09/es.md: -------------------------------------------------------------------------------- 1 | # Módulo 5. Clase 9. Contexto de la llamada de una función y this 2 | 3 | ## Ejemplo 1 - Taller de joyería 4 | 5 | Escriba un método `calcTotalPrice(stoneName)` que tome el nombre de una piedra 6 | y calcule y devuelva el precio total de las piedras con ese nombre, precio y 7 | cantidad según la propiedad `stones`. 8 | 9 | ```js 10 | const chopShop = { 11 | stones: [ 12 | { name: 'Emerald', price: 1300, quantity: 4 }, 13 | { name: 'Diamond', price: 2700, quantity: 3 }, 14 | { name: 'Sapphire', price: 1400, quantity: 7 }, 15 | { name: 'Ruby', price: 800, quantity: 2 }, 16 | ], 17 | calcTotalPrice(stoneName) {}, 18 | }; 19 | 20 | console.log(chopShop.calcTotalPrice('Emerald')); // 5200 21 | console.log(chopShop.calcTotalPrice('Diamond')); // 8100 22 | console.log(chopShop.calcTotalPrice('Sapphire')); // 9800 23 | console.log(chopShop.calcTotalPrice('Ruby')); // 1600 24 | ``` 25 | 26 | ## Ejemplo 2 - Guía telefónica 27 | 28 | Refactoriza los métodos del objeto `phonebook` para que el código funcione. 29 | 30 | ```js 31 | const phonebook = { 32 | contacts: [], 33 | add(contact) { 34 | const newContact = { 35 | list: 'default', 36 | ...contact, 37 | id: generateId(), 38 | createdAt: getDate(), 39 | }; 40 | contacts.push(newContact); 41 | }, 42 | generateId() { 43 | return '_' + Math.random().toString(36).substr(2, 9); 44 | }, 45 | getDate() { 46 | return Date.now(); 47 | }, 48 | }; 49 | 50 | console.log( 51 | phonebook.add({ 52 | name: 'Mango', 53 | email: 'mango@mail.com', 54 | list: 'friends', 55 | }), 56 | ); 57 | console.log( 58 | phonebook.add({ 59 | name: 'Poly', 60 | email: 'poly@hotmail.com', 61 | }), 62 | ); 63 | ``` 64 | 65 | ## Ejemplo 3 - Calculadora 66 | 67 | Crea un objeto `calculator` con tres métodos: 68 | 69 | - `read(a, b)`- toma dos valores y los almacena como propiedades del objeto. 70 | - `add()` - devuelve la suma de los valores almacenados. 71 | - `mult()` - multiplica los valores almacenados y devuelve el resultado. 72 | 73 | ```js 74 | const calculator = {}; 75 | ``` 76 | -------------------------------------------------------------------------------- /lesson-09/ru.md: -------------------------------------------------------------------------------- 1 | # Модуль 5. Занятие 9. Контекст вызова функции и this 2 | 3 | ## Example 1 - Мастерская драгоценностей 4 | 5 | Напишите метод `calcTotalPrice(stoneName)`, который принимает название камня и 6 | рассчитывает и возвращает общую стоимость камней с таким именем, ценой и 7 | количеством из свойства `stones`. 8 | 9 | ```js 10 | const chopShop = { 11 | stones: [ 12 | { name: 'Emerald', price: 1300, quantity: 4 }, 13 | { name: 'Diamond', price: 2700, quantity: 3 }, 14 | { name: 'Sapphire', price: 1400, quantity: 7 }, 15 | { name: 'Ruby', price: 800, quantity: 2 }, 16 | ], 17 | calcTotalPrice(stoneName) {}, 18 | }; 19 | 20 | console.log(chopShop.calcTotalPrice('Emerald')); // 5200 21 | console.log(chopShop.calcTotalPrice('Diamond')); // 8100 22 | console.log(chopShop.calcTotalPrice('Sapphire')); // 9800 23 | console.log(chopShop.calcTotalPrice('Ruby')); // 1600 24 | ``` 25 | 26 | ## Example 2 - Телефонная книга 27 | 28 | Выполните рефакторинг методов объекта `phonebook` чтобы код заработал. 29 | 30 | ```js 31 | const phonebook = { 32 | contacts: [], 33 | add(contact) { 34 | const newContact = { 35 | list: 'default', 36 | ...contact, 37 | id: generateId(), 38 | createdAt: getDate(), 39 | }; 40 | contacts.push(newContact); 41 | }, 42 | generateId() { 43 | return '_' + Math.random().toString(36).substr(2, 9); 44 | }, 45 | getDate() { 46 | return Date.now(); 47 | }, 48 | }; 49 | 50 | console.log( 51 | phonebook.add({ 52 | name: 'Mango', 53 | email: 'mango@mail.com', 54 | list: 'friends', 55 | }), 56 | ); 57 | console.log( 58 | phonebook.add({ 59 | name: 'Poly', 60 | email: 'poly@hotmail.com', 61 | }), 62 | ); 63 | ``` 64 | 65 | ## Example 3 - Калькулятор 66 | 67 | Создайте объект `calculator` с тремя методами: 68 | 69 | - `read(a, b)`- принимает два значения и сохраняет их как свойства объекта. 70 | - `add()` - возвращает сумму сохранённых значений. 71 | - `mult()` - перемножает сохранённые значения и возвращает результат. 72 | 73 | ```js 74 | const calculator = {}; 75 | ``` 76 | -------------------------------------------------------------------------------- /lesson-09/uk.md: -------------------------------------------------------------------------------- 1 | # Модуль 5. Заняття 9. Контекст виклику функції та this 2 | 3 | ## Example 1 - Майстерня коштовностей 4 | 5 | Напишіть метод `calcTotalPrice(stoneName)`, який приймає назву каменю і 6 | розраховує та повертає загальну вартість каменів з таким ім'ям, ціною та 7 | кількістю з властивості `stones`. 8 | 9 | ```js 10 | const chopShop = { 11 | stones: [ 12 | { name: 'Emerald', price: 1300, quantity: 4 }, 13 | { name: 'Diamond', price: 2700, quantity: 3 }, 14 | { name: 'Sapphire', price: 1400, quantity: 7 }, 15 | { name: 'Ruby', price: 800, quantity: 2 }, 16 | ], 17 | calcTotalPrice(stoneName) {}, 18 | }; 19 | 20 | console.log(chopShop.calcTotalPrice('Emerald')); // 5200 21 | console.log(chopShop.calcTotalPrice('Diamond')); // 8100 22 | console.log(chopShop.calcTotalPrice('Sapphire')); // 9800 23 | console.log(chopShop.calcTotalPrice('Ruby')); // 1600 24 | ``` 25 | 26 | ## Example 2 - Телефонна книга 27 | 28 | Виконайте рефакторинг методів об'єкту `phonebook` щоб код запрацював. 29 | 30 | ```js 31 | const phonebook = { 32 | contacts: [], 33 | add(contact) { 34 | const newContact = { 35 | list: 'default', 36 | ...contact, 37 | id: generateId(), 38 | createdAt: getDate(), 39 | }; 40 | contacts.push(newContact); 41 | }, 42 | generateId() { 43 | return '_' + Math.random().toString(36).substr(2, 9); 44 | }, 45 | getDate() { 46 | return Date.now(); 47 | }, 48 | }; 49 | 50 | console.log( 51 | phonebook.add({ 52 | name: 'Mango', 53 | email: 'mango@mail.com', 54 | list: 'friends', 55 | }), 56 | ); 57 | console.log( 58 | phonebook.add({ 59 | name: 'Poly', 60 | email: 'poly@hotmail.com', 61 | }), 62 | ); 63 | ``` 64 | 65 | ## Example 3 - Калькулятор 66 | 67 | Створіть об'єкт `calculator` з трьома методами: 68 | 69 | - `read(a, b)`- приймає два значення та зберігає їх як властивості об'єкта. 70 | - `add()` - повертає суму збережених значень. 71 | - `mult()` - перемножує збережені значення та повертає результат. 72 | 73 | ```js 74 | const calculator = {}; 75 | ``` 76 | -------------------------------------------------------------------------------- /lesson-10/en.md: -------------------------------------------------------------------------------- 1 | # Module 5 - Lesson 10 - Prototypes and classes 2 | 3 | ## Example 1 - Blogger 4 | 5 | Write a `Blogger` class to create a blogger object with the following properties: 6 | 7 | - `email` - mail, line 8 | - `age` - age, number 9 | - `numberOfPosts` - number of posts, number 10 | - `topics` - an array of topics the blogger specializes in 11 | 12 | The class expects one parameter - object of settings with the same name properties. 13 | 14 | Add a `getInfo()` method that returns string: 15 | `User ${mail} is ${age} years old and has ${number of posts} posts`. 16 | 17 | Add the `updatePostCount(value)` method, which in the `value` parameter takes 18 | number of posts to add to the user. 19 | 20 | ```js 21 | const mango = new User({ 22 | name: 'mango@mail.com', 23 | age: 24, 24 | numberOfPosts: 20, 25 | topics: ['tech', 'cooking'], 26 | }); 27 | console.log(mango.getInfo()); // User mango@mail.com is 24 years old and has 20 posts 28 | mango.updatePostCount(5); 29 | console.log(mango.getInfo()); // User mango@mail.com is 24 years old and has 25 posts 30 | 31 | const poly = new User({ 32 | name: 'poly@mail.com', 33 | age: 19, 34 | numberOfPosts: 17, 35 | topics: ['sports', 'gaming', 'health'], 36 | }); 37 | console.log(poly.getInfo()); // User poly@mail.com is 19 years old and has 17 posts 38 | poly.updatePostCount(4); 39 | console.log(poly.getInfo()); // User poly@mail.com is 19 years old and has 21 posts 40 | ``` 41 | 42 | ## Example 2 - Storagе 43 | 44 | Write a `Storage` class that creates objects for managing a warehouse of goods. 45 | When called, it will receive one argument - the initial array of goods, and write 46 | it to the `items` property. 47 | 48 | Add class methods: 49 | 50 | - `getItems()` - returns an array of products. 51 | - `addItem(item)` - receives a new product and adds it to the current ones. 52 | - `removeItem(item)` - receives the product and, if it exists, removes it from the current. 53 | 54 | ```js 55 | const storage = new Storage(['🍎', '🍋', '🍇', '🍑']); 56 | 57 | const items = storage.getItems(); 58 | console.table(items); // [ '🍎', '🍋', '🍇', '🍑' ] 59 | 60 | storage.addItem('🍌'); 61 | console.table(storage.items); // [ '🍎', '🍋', '🍇', '🍑', '🍌' ] 62 | 63 | storage.removeItem('🍋'); 64 | console.table(storage.items); // [ '🍎', '🍇', '🍑', '🍌' ] 65 | ``` 66 | 67 | ## Example 3 - User 68 | 69 | Write a class `User` which creates an object with properties `login` and `email`. 70 | Declare private properties `#login` and `#email`, which can be accessed via 71 | getter and setter of `login` and `email`. 72 | 73 | ```js 74 | const mango = new User({ 75 | login: 'Mango', 76 | email: 'mango@dog.woof', 77 | }); 78 | 79 | console.log(mango.login); // Mango 80 | mango.login = 'Mangodoge'; 81 | console.log(mango.login); // Mangodoge 82 | 83 | const poly = new User({ 84 | login: 'Poly', 85 | email: 'poly@mail.com', 86 | }); 87 | 88 | console.log(poly.login); // Poly 89 | poly.login = 'Polycutie'; 90 | console.log(poly.login); // Polycutie 91 | ``` 92 | 93 | ## Example 4 - Notes 94 | 95 | Write a `Notes` class that manages the collection of notes in the `items` property. 96 | A note is an object with `text` and `priority` properties. Add a static 97 | property `Priority` to the class, which will store the object with priorities. 98 | 99 | ```js 100 | { 101 | LOW: 'low', 102 | NORMAL: 'normal', 103 | HIGH: 'high' 104 | } 105 | ``` 106 | 107 | Add methods`addNote(note)`, `removeNote(text)` and 108 | `updatePriority(text, newPriority)`. 109 | 110 | ```js 111 | const myNotes = new Notes([]); 112 | 113 | myNotes.addNote({ text: 'My first note', priority: Notes.Priority.LOW }); 114 | console.log(myNotes.items); 115 | 116 | myNotes.addNote({ 117 | text: 'My second note', 118 | priority: Notes.Priority.NORMAL, 119 | }); 120 | console.log(myNotes.items); 121 | 122 | myNotes.removeNote('My first note'); 123 | console.log(myNotes.items); 124 | 125 | myNotes.updateNote('My second note', Notes.Priority.HIGH); 126 | console.log(myNotes.items); 127 | ``` 128 | 129 | ## Example 5 - Toggle 130 | 131 | Write a `Toggle` class that takes a settings object `{isOpen: boolean}` and 132 | declares one property `on` - state on/off (true/false). By default 133 | the value of the `on` property should be `false`. 134 | 135 | ```js 136 | const firstToggle = new Toggle({ isOpen: true }); 137 | console.group('firstToggle'); 138 | console.log(firstToggle.on); 139 | firstToggle.toggle(); 140 | console.log(firstToggle.on); 141 | console.groupEnd('firstToggle'); 142 | 143 | const secondToggle = new Toggle(); 144 | console.group('secondToggle'); 145 | console.log(secondToggle.on); 146 | secondToggle.toggle(); 147 | console.log(secondToggle.on); 148 | console.groupEnd('secondToggle'); 149 | ``` 150 | -------------------------------------------------------------------------------- /lesson-10/es.md: -------------------------------------------------------------------------------- 1 | # Módulo 5. Clase 10. Prototipos y Clases 2 | 3 | ## Ejemplo 1 - Blogger 4 | 5 | Escribe una clase `Blogger` para crear un objeto blogger con las siguientes propiedades: 6 | 7 | - `email` - correo, cadena 8 | - `age` - edad, número 9 | - `numberOfPosts` - cantidad de posts, número 10 | - `topics` - un Array de temas en los que el blogger se especializa 11 | 12 | La clase espera un único parámetro: un objeto de configuraciones con propiedades del mismo nombre. 13 | 14 | Agrega el método `getInfo()`, que devuelde la cadena: 15 | `User ${correo} is ${edad} years old and has ${cant. de posts} posts`. 16 | 17 | Agrega el método `updatePostCount(value)`, que en el parámetro `value` recibe la 18 | cantidad de posts que debe añadir el usuario. 19 | 20 | ```js 21 | const mango = new User({ 22 | name: 'mango@mail.com', 23 | age: 24, 24 | numberOfPosts: 20, 25 | topics: ['tech', 'cooking'], 26 | }); 27 | console.log(mango.getInfo()); // User mango@mail.com is 24 years old and has 20 posts 28 | mango.updatePostCount(5); 29 | console.log(mango.getInfo()); // User mango@mail.com is 24 years old and has 25 posts 30 | 31 | const poly = new User({ 32 | name: 'poly@mail.com', 33 | age: 19, 34 | numberOfPosts: 17, 35 | topics: ['sports', 'gaming', 'health'], 36 | }); 37 | console.log(poly.getInfo()); // User poly@mail.com is 19 years old and has 17 posts 38 | poly.updatePostCount(4); 39 | console.log(poly.getInfo()); // User poly@mail.com is 19 years old and has 21 posts 40 | ``` 41 | 42 | ## Ejemplo 2 - Almacén 43 | 44 | Escriba una clase `Storage` que crea objetos para gestionar un almacén de productos. 45 | Cuando se llama recibe un argumento, el array inicial de productos, y lo escribe 46 | en la propiedad `items`. 47 | 48 | Añade métodos de la clase: 49 | 50 | - `getItems()` - devuelve un array de productos. 51 | - `addItem(item)` - recibe un nuevo producto y lo añade a los actuales. 52 | - `removeItem(item)` - recibe el elemento y, si existe, lo elimina de los actuales. 53 | 54 | ```js 55 | const storage = new Storage(['🍎', '🍋', '🍇', '🍑']); 56 | 57 | const items = storage.getItems(); 58 | console.table(items); // [ '🍎', '🍋', '🍇', '🍑' ] 59 | 60 | storage.addItem('🍌'); 61 | console.table(storage.items); // [ '🍎', '🍋', '🍇', '🍑', '🍌' ] 62 | 63 | storage.removeItem('🍋'); 64 | console.table(storage.items); // [ '🍎', '🍇', '🍑', '🍌' ] 65 | ``` 66 | 67 | ## Ejemplo 3 - User 68 | 69 | Escribe una clase `User` que cree un objeto con las propiedades `login` y `email`. 70 | Declare las propiedades privadas `#login` y `#email`, a las que se puede acceder 71 | mediante el getter y setter `login` y `email`. 72 | 73 | ```js 74 | const mango = new User({ 75 | login: 'Mango', 76 | email: 'mango@dog.woof', 77 | }); 78 | 79 | console.log(mango.login); // Mango 80 | mango.login = 'Mangodoge'; 81 | console.log(mango.login); // Mangodoge 82 | 83 | const poly = new User({ 84 | login: 'Poly', 85 | email: 'poly@mail.com', 86 | }); 87 | 88 | console.log(poly.login); // Poly 89 | poly.login = 'Polycutie'; 90 | console.log(poly.login); // Polycutie 91 | ``` 92 | 93 | ## Ejemplo 4 - Notas 94 | 95 | Escribe una clase `Notes` que gestione una colección de notas en la propiedad `items`. 96 | Una nota es un objeto con las propiedades `text` y `priority`. Añade una propiedad 97 | estática `Prioridad` a la clase, en donde almacenará el objeto con las prioridades. 98 | 99 | ```js 100 | { 101 | LOW: 'low', 102 | NORMAL: 'normal', 103 | HIGH: 'high' 104 | } 105 | ``` 106 | 107 | Agregue los métodos `addNote(note)`, `removeNote(text)` y 108 | `updatePriority(text, newPriority)`. 109 | 110 | ```js 111 | const myNotes = new Notes([]); 112 | 113 | myNotes.addNote({ text: 'Mi primera nota', priority: Notes.Priority.LOW }); 114 | console.log(myNotes.items); 115 | 116 | myNotes.addNote({ 117 | text: 'Mi segunda nota', 118 | priority: Notes.Priority.NORMAL, 119 | }); 120 | console.log(myNotes.items); 121 | 122 | myNotes.removeNote('Mi primera nota'); 123 | console.log(myNotes.items); 124 | 125 | myNotes.updateNote('Mi segunda nota', Notes.Priority.HIGH); 126 | console.log(myNotes.items); 127 | ``` 128 | 129 | ## Ejemplo 5 - Toggle 130 | 131 | Escribe una clase `Toggle` que toma un objeto de configuración `{isOpen: boolean}` y 132 | declara una propiedad `on` - estado on/off (verdadero/falso). Por defecto el valor 133 | de la propiedad `on` debe ser `false`. 134 | 135 | ```js 136 | const firstToggle = new Toggle({ isOpen: true }); 137 | console.group('firstToggle'); 138 | console.log(firstToggle.on); 139 | firstToggle.toggle(); 140 | console.log(firstToggle.on); 141 | console.groupEnd('firstToggle'); 142 | 143 | const secondToggle = new Toggle(); 144 | console.group('secondToggle'); 145 | console.log(secondToggle.on); 146 | secondToggle.toggle(); 147 | console.log(secondToggle.on); 148 | console.groupEnd('secondToggle'); 149 | ``` 150 | -------------------------------------------------------------------------------- /lesson-10/ru.md: -------------------------------------------------------------------------------- 1 | # Модуль 5. Занятие 10. Прототипы и классы 2 | 3 | ## Example 1 - Блоггер 4 | 5 | Напиши класс `Blogger` для создания обьекта блоггера со следующим свойствами: 6 | 7 | - `email` - почта, строка 8 | - `age` - возраст, число 9 | - `numberOfPosts` - кол-во постов, число 10 | - `topics` - массив тем на которых специализируется блоггер 11 | 12 | Класс ожидает один параметр - объект настроек с одноимёнными свойствами. 13 | 14 | Добавь метод `getInfo()`, который, возвращает строку: 15 | `User ${почта} is ${возраст} years old and has ${кол-во постов} posts`. 16 | 17 | Добавь метод `updatePostCount(value)`, который в параметре `value` принимает 18 | количество постов которые нужно добавить пользователю. 19 | 20 | ```js 21 | const mango = new User({ 22 | name: 'mango@mail.com', 23 | age: 24, 24 | numberOfPosts: 20, 25 | topics: ['tech', 'cooking'], 26 | }); 27 | console.log(mango.getInfo()); // User mango@mail.com is 24 years old and has 20 posts 28 | mango.updatePostCount(5); 29 | console.log(mango.getInfo()); // User mango@mail.com is 24 years old and has 25 posts 30 | 31 | const poly = new User({ 32 | name: 'poly@mail.com', 33 | age: 19, 34 | numberOfPosts: 17, 35 | topics: ['sports', 'gaming', 'health'], 36 | }); 37 | console.log(poly.getInfo()); // User poly@mail.com is 19 years old and has 17 posts 38 | poly.updatePostCount(4); 39 | console.log(poly.getInfo()); // User poly@mail.com is 19 years old and has 21 posts 40 | ``` 41 | 42 | ## Example 2 - Хранилище 43 | 44 | Напиши класс `Storage` который создаёт объекты для управления складом товаров. 45 | При вызове будет получать один аргумент - начальный массив товаров, и записывать 46 | его в свойство `items`. 47 | 48 | Добавь методы класса: 49 | 50 | - `getItems()` - возвращает массив товаров. 51 | - `addItem(item)` - получает новый товар и добавляет его к текущим. 52 | - `removeItem(item)` - получает товар и, если он есть, удаляет его из текущих. 53 | 54 | ```js 55 | const storage = new Storage(['🍎', '🍋', '🍇', '🍑']); 56 | 57 | const items = storage.getItems(); 58 | console.table(items); // [ '🍎', '🍋', '🍇', '🍑' ] 59 | 60 | storage.addItem('🍌'); 61 | console.table(storage.items); // [ '🍎', '🍋', '🍇', '🍑', '🍌' ] 62 | 63 | storage.removeItem('🍋'); 64 | console.table(storage.items); // [ '🍎', '🍇', '🍑', '🍌' ] 65 | ``` 66 | 67 | ## Example 3 - User 68 | 69 | Напиши класс `User` который создаёт объект со свойствами `login` и `email`. 70 | Объяви приватные свойства `#login` и `#email`, доступ к которым сделай через 71 | геттер и сеттер `login` и `email`. 72 | 73 | ```js 74 | const mango = new User({ 75 | login: 'Mango', 76 | email: 'mango@dog.woof', 77 | }); 78 | 79 | console.log(mango.login); // Mango 80 | mango.login = 'Mangodoge'; 81 | console.log(mango.login); // Mangodoge 82 | 83 | const poly = new User({ 84 | login: 'Poly', 85 | email: 'poly@mail.com', 86 | }); 87 | 88 | console.log(poly.login); // Poly 89 | poly.login = 'Polycutie'; 90 | console.log(poly.login); // Polycutie 91 | ``` 92 | 93 | ## Example 4 - Заметки 94 | 95 | Напиши класс `Notes` который управляет коллекцией заметок в свойстве `items`. 96 | Заметка это объект со свойствами `text` и `priority`. Добавь классу статическое 97 | свойство `Priority`, в котором будет храниться объект с приоритетами. 98 | 99 | ```js 100 | { 101 | LOW: 'low', 102 | NORMAL: 'normal', 103 | HIGH: 'high' 104 | } 105 | ``` 106 | 107 | Добавь методы `addNote(note)`, `removeNote(text)` и 108 | `updatePriority(text, newPriority)`. 109 | 110 | ```js 111 | const myNotes = new Notes([]); 112 | 113 | myNotes.addNote({ text: 'Моя первая заметка', priority: Notes.Priority.LOW }); 114 | console.log(myNotes.items); 115 | 116 | myNotes.addNote({ 117 | text: 'Моя вторая заметка', 118 | priority: Notes.Priority.NORMAL, 119 | }); 120 | console.log(myNotes.items); 121 | 122 | myNotes.removeNote('Моя первая заметка'); 123 | console.log(myNotes.items); 124 | 125 | myNotes.updateNote('Моя вторая заметка', Notes.Priority.HIGH); 126 | console.log(myNotes.items); 127 | ``` 128 | 129 | ## Example 5 - Toggle 130 | 131 | Напишите класс `Toggle` который принимает объект настроек `{isOpen: boolean}` и 132 | объявляет одно свойство `on` - состояние вкл/выкл (true/false). По умолчанию 133 | значение свойства `on` должно быть `false`. 134 | 135 | ```js 136 | const firstToggle = new Toggle({ isOpen: true }); 137 | console.group('firstToggle'); 138 | console.log(firstToggle.on); 139 | firstToggle.toggle(); 140 | console.log(firstToggle.on); 141 | console.groupEnd('firstToggle'); 142 | 143 | const secondToggle = new Toggle(); 144 | console.group('secondToggle'); 145 | console.log(secondToggle.on); 146 | secondToggle.toggle(); 147 | console.log(secondToggle.on); 148 | console.groupEnd('secondToggle'); 149 | ``` 150 | -------------------------------------------------------------------------------- /lesson-10/uk.md: -------------------------------------------------------------------------------- 1 | # Модуль 5. Заняття 10. Прототипи та класи 2 | 3 | ## Example 1 - Блогер 4 | 5 | Напиши клас `Blogger` для створення об'єкта блогера з наступними властивостями: 6 | 7 | - `email` - пошта, рядок 8 | - `age` - вік, число 9 | - `numberOfPosts` - кількість постів, число 10 | - `topics` - масив тем на яких спеціалізується блогер 11 | 12 | Клас чекає один параметр - об'єкт налаштувань з однойменними властивостями. 13 | 14 | Додай метод `getInfo()`, який, повертає рядок: 15 | `User ${пошта} is ${вік} years old and has ${кількість постів} posts`. 16 | 17 | Додай метод `updatePostCount(value)`, який у параметрі `value` приймає 18 | кількість постів, які потрібно додати користувачеві. 19 | 20 | ```js 21 | const mango = new User({ 22 | name: 'mango@mail.com', 23 | age: 24, 24 | numberOfPosts: 20, 25 | topics: ['tech', 'cooking'], 26 | }); 27 | console.log(mango.getInfo()); // User mango@mail.com is 24 years old and has 20 posts 28 | mango.updatePostCount(5); 29 | console.log(mango.getInfo()); // User mango@mail.com is 24 years old and has 25 posts 30 | 31 | const poly = new User({ 32 | name: 'poly@mail.com', 33 | age: 19, 34 | numberOfPosts: 17, 35 | topics: ['sports', 'gaming', 'health'], 36 | }); 37 | console.log(poly.getInfo()); // User poly@mail.com is 19 years old and has 17 posts 38 | poly.updatePostCount(4); 39 | console.log(poly.getInfo()); // User poly@mail.com is 19 years old and has 21 posts 40 | ``` 41 | 42 | ## Example 2 - Сховище 43 | 44 | Напиши клас `Storage` який створює об'єкти для керування складом товарів. 45 | При виклику отримуватиме один аргумент - початковий масив товарів і записуватиме 46 | його властивість `items`. 47 | 48 | Додай методи класу: 49 | 50 | - `getItems()` - повертає масив товарів. 51 | - `addItem(item)` - отримує новий товар і додає його до поточних. 52 | - `removeItem(item)` - отримує товар і, якщо він є, видаляє його з поточних. 53 | 54 | ```js 55 | const storage = new Storage(['🍎', '🍋', '🍇', '🍑']); 56 | 57 | const items = storage.getItems(); 58 | console.table(items); // [ '🍎', '🍋', '🍇', '🍑' ] 59 | 60 | storage.addItem('🍌'); 61 | console.table(storage.items); // [ '🍎', '🍋', '🍇', '🍑', '🍌' ] 62 | 63 | storage.removeItem('🍋'); 64 | console.table(storage.items); // [ '🍎', '🍇', '🍑', '🍌' ] 65 | ``` 66 | 67 | ## Example 3 - User 68 | 69 | Напиши клас `User` який створює об'єкт із властивостями `login` та `email`. 70 | Оголоси приватні властивості `#login` та `#email`, доступ до яких зроби через 71 | гетер та сетер `login` та `email`. 72 | 73 | ```js 74 | const mango = new User({ 75 | login: 'Mango', 76 | email: 'mango@dog.woof', 77 | }); 78 | 79 | console.log(mango.login); // Mango 80 | mango.login = 'Mangodoge'; 81 | console.log(mango.login); // Mangodoge 82 | 83 | const poly = new User({ 84 | login: 'Poly', 85 | email: 'poly@mail.com', 86 | }); 87 | 88 | console.log(poly.login); // Poly 89 | poly.login = 'Polycutie'; 90 | console.log(poly.login); // Polycutie 91 | ``` 92 | 93 | ## Example 4 - Нотатки 94 | 95 | Напиши клас `Notes` який керує колекцією нотаток у властивості `items`. 96 | Замітка це об'єкт із властивостями `text` та `priority`. Додай класу статичну 97 | властивість `Priority`, у якому зберігатиметься об'єкт із пріоритетами. 98 | 99 | ```js 100 | { 101 | LOW: 'low', 102 | NORMAL: 'normal', 103 | HIGH: 'high' 104 | } 105 | ``` 106 | 107 | Додай методи `addNote(note)`, `removeNote(text)` та 108 | `updatePriority(text, newPriority)`. 109 | 110 | ```js 111 | const myNotes = new Notes([]); 112 | 113 | myNotes.addNote({ text: 'Моя перша замітка', priority: Notes.Priority.LOW }); 114 | console.log(myNotes.items); 115 | 116 | myNotes.addNote({ 117 | text: 'Моя друга замітка', 118 | priority: Notes.Priority.NORMAL, 119 | }); 120 | console.log(myNotes.items); 121 | 122 | myNotes.removeNote('Моя перша замітка'); 123 | console.log(myNotes.items); 124 | 125 | myNotes.updateNote('Моя друга замітка', Notes.Priority.HIGH); 126 | console.log(myNotes.items); 127 | ``` 128 | 129 | ## Example 5 - Toggle 130 | 131 | Напишіть клас `Toggle` який приймає об'єкт налаштувань `{isOpen: boolean}` і 132 | оголошує одну властивість `on` - стан вкл/викл (true/false). За замовчуванням 133 | значення властивості `on` повинно бути `false`. 134 | 135 | ```js 136 | const firstToggle = new Toggle({ isOpen: true }); 137 | console.group('firstToggle'); 138 | console.log(firstToggle.on); 139 | firstToggle.toggle(); 140 | console.log(firstToggle.on); 141 | console.groupEnd('firstToggle'); 142 | 143 | const secondToggle = new Toggle(); 144 | console.group('secondToggle'); 145 | console.log(secondToggle.on); 146 | secondToggle.toggle(); 147 | console.log(secondToggle.on); 148 | console.groupEnd('secondToggle'); 149 | ``` 150 | --------------------------------------------------------------------------------