From 0c3aedb15bf43151f7fa4183be198e8313cb643c Mon Sep 17 00:00:00 2001 From: Oleh Lobanov Date: Wed, 14 Aug 2019 16:42:09 +0300 Subject: [PATCH 1/2] 1_02_13 --- .../1-rewrite-switch-if-else/solution.md | 12 +- .../1-rewrite-switch-if-else/task.md | 8 +- .../13-switch/2-rewrite-if-switch/solution.md | 6 +- .../13-switch/2-rewrite-if-switch/task.md | 4 +- 1-js/02-first-steps/13-switch/article.md | 106 +++++++++--------- 5 files changed, 68 insertions(+), 68 deletions(-) diff --git a/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/solution.md b/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/solution.md index 5afbd9b00..0bc6283b7 100644 --- a/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/solution.md +++ b/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/solution.md @@ -1,6 +1,6 @@ -To precisely match the functionality of `switch`, the `if` must use a strict comparison `'==='`. +Щоб точно відповідати функціональності конструкції `switch`, `if` повинен використовувати строге порівняння `'==='`. -For given strings though, a simple `'=='` works too. +Хоча для даних рядків звичайне `'=='` працює також. ```js no-beautify if(browser == 'Edge') { @@ -9,12 +9,12 @@ if(browser == 'Edge') { || browser == 'Firefox' || browser == 'Safari' || browser == 'Opera') { - alert( 'Мы поддерживаем и эти браузерыo' ); + alert( 'Ми підтримуємо і ці браузери' ); } else { - alert( 'Надеемся, что эта страница выглядит хорошо!' ); + alert( 'Маємо надію, що ця сторінка виглядає добре!' ); } ``` -Please note: the construct `browser == 'Chrome' || browser == 'Firefox' …` is split into multiple lines for better readability. +Зверніть увагу: конструкція `browser == 'Chrome' || browser == 'Firefox' …` розділена на кілька рядків для кращої читабельності. -But the `switch` construct is still cleaner and more descriptive. +Але конструкція `switch` більш чистіша та наочніша. diff --git a/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/task.md b/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/task.md index acd01122b..55023389b 100644 --- a/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/task.md +++ b/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/task.md @@ -2,9 +2,9 @@ importance: 5 --- -# Rewrite the "switch" into an "if" +# Перепишіть конструкцію "switch" в аналогічну з використанням "if" -Write the code using `if..else` which would correspond to the following `switch`: +Напишіть код з використанням `if..else` та відповідає наступному в конструкції `switch`: ```js switch (browser) { @@ -16,10 +16,10 @@ switch (browser) { case 'Firefox': case 'Safari': case 'Opera': - alert( 'Мы поддерживаем и эти браузеры' ); + alert( 'Ми підтримуємо і ці браузери' ); break; default: - alert( 'Надеемся, что эта страница выглядит хорошо!' ); + alert( 'Маємо надію, що ця сторінка виглядає добре!' ); } ``` diff --git a/1-js/02-first-steps/13-switch/2-rewrite-if-switch/solution.md b/1-js/02-first-steps/13-switch/2-rewrite-if-switch/solution.md index ed87dd94b..35029b9a3 100644 --- a/1-js/02-first-steps/13-switch/2-rewrite-if-switch/solution.md +++ b/1-js/02-first-steps/13-switch/2-rewrite-if-switch/solution.md @@ -1,4 +1,4 @@ -The first two checks turn into two `case`. The third check is split into two cases: +Перші дві перевірки перетворюємо в два `case`. Третю перевірку розділяємо на два `case`: ```js run let a = +prompt('a?', ''); @@ -21,6 +21,6 @@ switch (a) { } ``` -Please note: the `break` at the bottom is not required. But we put it to make the code future-proof. +Зверніть увагу: `break` знизу не обов'язковий. Але ми його вказуємо, щоб зробити наш код більш надійним за умови майбутніх змін. -In the future, there is a chance that we'd want to add one more `case`, for example `case 4`. And if we forget to add a break before it, at the end of `case 3`, there will be an error. So that's a kind of self-insurance. +У майбутньому є можливість що ми додамо ще один блок `case`, наприклад `case 4`. В разі якщо ми забудемо додати `break` перед ним наприкінці коду з `case 3`, - ми отримаємо помилку у логіці роботи нашого коду. Таким чином це своєрідне самострахування. diff --git a/1-js/02-first-steps/13-switch/2-rewrite-if-switch/task.md b/1-js/02-first-steps/13-switch/2-rewrite-if-switch/task.md index ec99d098d..59227c412 100644 --- a/1-js/02-first-steps/13-switch/2-rewrite-if-switch/task.md +++ b/1-js/02-first-steps/13-switch/2-rewrite-if-switch/task.md @@ -2,9 +2,9 @@ importance: 4 --- -# Rewrite "if" into "switch" +# Перепишіть умови "if" в конструкцію "switch" -Rewrite the code below using a single `switch` statement: +Перепишіть код нижче використовуючи одну конструкцію `switch`: ```js run let a = +prompt('a?', ''); diff --git a/1-js/02-first-steps/13-switch/article.md b/1-js/02-first-steps/13-switch/article.md index dec40a537..a96b0e034 100644 --- a/1-js/02-first-steps/13-switch/article.md +++ b/1-js/02-first-steps/13-switch/article.md @@ -1,14 +1,14 @@ -# The "switch" statement +# Конструкція "switch" -A `switch` statement can replace multiple `if` checks. +Конструкція `switch` може замінити кілька `if`. -It gives a more descriptive way to compare a value with multiple variants. +Вона дає можливість більш наочного способу порівняння значення відразу з кількома варіантами. -## The syntax +## Синтаксис -The `switch` has one or more `case` blocks and an optional default. +Конструкція `switch` має один або більше `case` блоків та необов'язковий блок `default`. -It looks like this: +Вона виглядає так: ```js no-beautify switch(x) { @@ -26,71 +26,71 @@ switch(x) { } ``` -- The value of `x` is checked for a strict equality to the value from the first `case` (that is, `value1`) then to the second (`value2`) and so on. -- If the equality is found, `switch` starts to execute the code starting from the corresponding `case`, until the nearest `break` (or until the end of `switch`). -- If no case is matched then the `default` code is executed (if it exists). +- Значення змінної `x` перевіряється на строгу рівність (===) значенню із першого блоку `case` (яке дорівнює `value1`), потім значенню із другого блоку (`value2`) і так далі. +- Якщо строго рівне значення знайдено, то `switch` починає виконання коду із відповідного `case` до найближчого `break` або до кінця всієї конструкції `switch`. +- Якщо жодне `case`-значення не збігається - виконується код із блоку `default` (якщо він присутній). -## An example +## Приклад роботи -An example of `switch` (the executed code is highlighted): +Приклад використання `switch` (код який буде виконаний виділено): ```js run let a = 2 + 2; switch (a) { case 3: - alert( 'Too small' ); + alert( 'Замало' ); break; *!* case 4: - alert( 'Exactly!' ); + alert( 'Точнісінько!' ); break; */!* case 5: - alert( 'Too large' ); + alert( 'Забагато' ); break; default: - alert( "I don't know such values" ); + alert( 'Я не знаю таких значень' ); } ``` -Here the `switch` starts to compare `a` from the first `case` variant that is `3`. The match fails. +Тут `switch` починає порівнювати `a` з першим варіантом із `case`, який дорівнює `3`. Це не відповідає `a`. -Then `4`. That's a match, so the execution starts from `case 4` until the nearest `break`. +Потім з другим, який дорівнює `4`. Цей варіант відповідає `a`, таким чином буде виконано код з `case 4` до найближчого `break`. -**If there is no `break` then the execution continues with the next `case` without any checks.** +**Якщо `break` відсутній, то буде продовжено виконання коду по наступним блокам `case` без перевірок.** -An example without `break`: +Приклад без `break`: ```js run let a = 2 + 2; switch (a) { case 3: - alert( 'Too small' ); + alert( 'Замало' ); *!* case 4: - alert( 'Exactly!' ); + alert( 'Точнісінько!' ); case 5: - alert( 'Too big' ); + alert( 'Забагато' ); default: - alert( "I don't know such values" ); + alert( 'Я не знаю таких значень' ); */!* } ``` -In the example above we'll see sequential execution of three `alert`s: +В прикладі вище ми бачимо послідовне виконання трьох `alert`: ```js -alert( 'Exactly!' ); -alert( 'Too big' ); -alert( "I don't know such values" ); +alert( 'Точнісінько!' ); +alert( 'Забагато' ); +alert( 'Я не знаю таких значень' ); ``` ````smart header="Any expression can be a `switch/case` argument" -Both `switch` and `case` allow arbitrary expressions. +Обидва `switch` та `case` допускають будь-який вираз в якості аргументу. -For example: +Наприклад: ```js run let a = "1"; @@ -99,74 +99,74 @@ let b = 0; switch (+a) { *!* case b + 1: - alert("this runs, because +a is 1, exactly equals b+1"); + alert("виконано це, бо +a це 1, що строго дорівнює b + 1"); break; */!* default: - alert("this doesn't run"); + alert("це не буде виконано"); } ``` -Here `+a` gives `1`, that's compared with `b + 1` in `case`, and the corresponding code is executed. +Тут значення виразу `+a` буде `1`, що збігається з значенням виразу `b + 1` із блоку `case`, таким чином код із цього блоку буде виконано. ```` -## Grouping of "case" +## Групування "case" -Several variants of `case` which share the same code can be grouped. +Кілька варіантів блоку `case`, які використовують однаковий код, можуть бути згруповані. -For example, if we want the same code to run for `case 3` and `case 5`: +Наприклад, якщо ми бажаємо виконати один і той самий код для `case 3` та `case 5`: ```js run no-beautify let a = 2 + 2; switch (a) { case 4: - alert('Right!'); + alert('Вірно!'); break; *!* - case 3: // (*) grouped two cases + case 3: // (*) групуємо два блоки `case` case 5: - alert('Wrong!'); - alert("Why don't you take a math class?"); + alert('Невірно!'); + alert("Можливо вам варто відвідати урок математики?"); break; */!* default: - alert('The result is strange. Really.'); + alert('Результат виглядає дивно. Дійсно.'); } ``` -Now both `3` and `5` show the same message. +Тепер обидва варіанти `3` та `5` виводять однакове повідомлення. -The ability to "group" cases is a side-effect of how `switch/case` works without `break`. Here the execution of `case 3` starts from the line `(*)` and goes through `case 5`, because there's no `break`. +Можливість групування блоків `case` - це побічний ефект того, як `switch/case` працює без `break`. Тут виконання коду `case 3` починається з рядка `(*)` та проходить через `case 5`, бо немає `break`. -## Type matters +## Тип має значення -Let's emphasize that the equality check is always strict. The values must be of the same type to match. +Необхідно наголосити, що перевірка відповідності є завжди строгою. Значення повинні бути однакового типу аби вони збігалися. -For example, let's consider the code: +Наприклад, розглянемо наступний код: ```js run -let arg = prompt("Enter a value?"); +let arg = prompt("Введіть значення?"); switch (arg) { case '0': case '1': - alert( 'One or zero' ); + alert( 'Один або нуль' ); break; case '2': - alert( 'Two' ); + alert( 'Два' ); break; case 3: - alert( 'Never executes!' ); + alert( 'Ніколи не буде виконано!' ); break; default: - alert( 'An unknown value' ); + alert( 'Невідоме значення' ); } ``` -1. For `0`, `1`, the first `alert` runs. -2. For `2` the second `alert` runs. -3. But for `3`, the result of the `prompt` is a string `"3"`, which is not strictly equal `===` to the number `3`. So we've got a dead code in `case 3`! The `default` variant will execute. +1. Для `0` та `1` буде виконано перший `alert`. +2. Для `2` - другий `alert`. +3. Але для `3`: результат виконання `prompt` є строкове значення `"3"`, яке строго не дорівнює `===` числу `3`. Таким чином ми маємо "мертвий код" в блоці `case 3`! Буде виконано код блоку `default`. From d8198055b8b7b9511a0f344f68333363db47e9d3 Mon Sep 17 00:00:00 2001 From: Oleh Lobanov Date: Wed, 14 Aug 2019 17:45:36 +0300 Subject: [PATCH 2/2] Fix small issues --- .../13-switch/1-rewrite-switch-if-else/solution.md | 2 +- 1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/task.md | 2 +- 1-js/02-first-steps/13-switch/2-rewrite-if-switch/solution.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/solution.md b/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/solution.md index 9c507e47f..d80e44b46 100644 --- a/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/solution.md +++ b/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/solution.md @@ -1,6 +1,6 @@ Щоб точно відповідати функціональності конструкції `switch`, `if` повинен використовувати строге порівняння `'==='`. -Хоча для даних рядків звичайне `'=='` працює також. +Хоча для даних рядків звичайне `'=='` також працює. ```js no-beautify if(browser == 'Edge') { diff --git a/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/task.md b/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/task.md index d8f02a303..152245a4b 100644 --- a/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/task.md +++ b/1-js/02-first-steps/13-switch/1-rewrite-switch-if-else/task.md @@ -4,7 +4,7 @@ importance: 5 # Перепишіть конструкцію "switch" в аналогічну з використанням "if" -Напишіть код з використанням `if..else` та відповідає наступному в конструкції `switch`: +Напишіть код з використанням `if..else`, що відповідає наступній конструкції `switch`: ```js switch (browser) { diff --git a/1-js/02-first-steps/13-switch/2-rewrite-if-switch/solution.md b/1-js/02-first-steps/13-switch/2-rewrite-if-switch/solution.md index 35029b9a3..223156c09 100644 --- a/1-js/02-first-steps/13-switch/2-rewrite-if-switch/solution.md +++ b/1-js/02-first-steps/13-switch/2-rewrite-if-switch/solution.md @@ -21,6 +21,6 @@ switch (a) { } ``` -Зверніть увагу: `break` знизу не обов'язковий. Але ми його вказуємо, щоб зробити наш код більш надійним за умови майбутніх змін. +Зверніть увагу: `break` знизу не обов'язковий. Але ми його вказуємо, щоб зробити наш код надійнішим за умови майбутніх змін. У майбутньому є можливість що ми додамо ще один блок `case`, наприклад `case 4`. В разі якщо ми забудемо додати `break` перед ним наприкінці коду з `case 3`, - ми отримаємо помилку у логіці роботи нашого коду. Таким чином це своєрідне самострахування.