chore(i18n,learn): processed translations (#50031)

This commit is contained in:
camperbot
2023-04-10 10:41:00 -05:00
committed by GitHub
parent c21ca3c6d0
commit 87634b35e1
201 changed files with 584 additions and 584 deletions
@@ -11,7 +11,7 @@ dashedName: escape-sequences-in-strings
الاقتباسات (quotes) ليست الرموز الوحيدة التي يمكن أن تكتب <dfn>مخرَّجة</dfn> (escaped) داخل مقطع نصي (string). تتيح لك escape sequences استخدام الرموز التي لا تمكن استعمالها في مقطع ما بدونهم.
<table class='table table-striped'><thead><tr><th>الكود</th><th>الناتج</th></tr></thead><tbody><tr><td><code>\'</code></td><td>single quote</td></tr><tr><td><code>\"</code></td><td>double quote</td></tr><tr><td><code>\\</code></td><td>backslash</td></tr><tr><td><code>\n</code></td><td>newline</td></tr><tr><td><code>\t</code></td><td>tab</td></tr><tr><td><code>\r</code></td><td>carriage return</td></tr><tr><td><code>\b</code></td><td>word boundary</td></tr><tr><td><code>\f</code></td><td>form feed</td></tr></tbody></table>
<table class='table table-striped'><thead><tr><th>الكود</th><th>الناتج</th></tr></thead><tbody><tr><td><code>\'</code></td><td>single quote</td></tr><tr><td><code>\"</code></td><td>double quote</td></tr><tr><td><code>\\</code></td><td>backslash</td></tr><tr><td><code>\n</code></td><td>newline</td></tr><tr><td><code>\t</code></td><td>tab</td></tr><tr><td><code>\r</code></td><td>carriage return</td></tr><tr><td><code>\b</code></td><td>backspace</td></tr><tr><td><code>\f</code></td><td>form feed</td></tr></tbody></table>
*لاحظ أن يجب أن يكون الخط المائل (backslash) نفسه يخرَّج (escaped) ليتم عرضه كخط مائل backslash.*
@@ -9,7 +9,7 @@ dashedName: selecting-from-many-options-with-switch-statements
# --description--
إن كنت تريد الاختيار بين خيارات كثيرة، استخدم عبارة <dfn>switch</dfn>. تختبر عبارة `switch` قيمة، ومن الأمكن أن تحتوي على عديد من عبارات <dfn>case</dfn> التي تحدد قيم مختلفة ممكنة. يتم تنفيذ العبارات من أول قيمة `case` متطابقة حتى يتم العثور على `break`.
If you need to match one value against many options, you can use a <dfn>switch</dfn> statement. A `switch` statement compares the value to the <dfn>case</dfn> statements which define various possible values. Any valid JavaScript statements can be executed inside a <dfn>case</dfn> block and will run from the first matched `case` value until a `break` is encountered.
فيما يلي مثال على عبارة `switch`:
@@ -11,7 +11,7 @@ dashedName: escape-sequences-in-strings
引號不是字符串中唯一可以被轉義(<dfn>escaped</dfn>)的字符。 轉義字符允許你使用可能無法在字符串中使用的字符。
<table class='table table-striped'><thead><tr><th>代碼</th><th>輸出</th></tr></thead><tbody><tr><td><code>\'</code></td><td>單引號</td></tr><tr><td><code>\"</code></td><td>雙引號</td></tr><tr><td><code>\\</code></td><td>反斜槓</td></tr><tr><td><code>\n</code></td><td>換行符</td></tr><tr><td><code>\t</code></td><td>製表符</td></tr><tr><td><code>\r</code></td><td>回車</td></tr><tr><td><code>\b</code></td><td>退格</td></tr><tr><td><code>\f</code></td><td>換頁符</td></tr></tbody></table>
<table class='table table-striped'><thead><tr><th>代碼</th><th>輸出</th></tr></thead><tbody><tr><td><code>\'</code></td><td>單引號</td></tr><tr><td><code>\"</code></td><td>雙引號</td></tr><tr><td><code>\\</code></td><td>反斜槓</td></tr><tr><td><code>\n</code></td><td>換行符</td></tr><tr><td><code>\t</code></td><td>製表符</td></tr><tr><td><code>\r</code></td><td>回車</td></tr><tr><td><code>\b</code></td><td>backspace</td></tr><tr><td><code>\f</code></td><td>換頁符</td></tr></tbody></table>
*請注意,反斜線本身必須被轉義,才能顯示爲反斜線。*
@@ -9,7 +9,7 @@ dashedName: selecting-from-many-options-with-switch-statements
# --description--
如果你有非常多的選項需要選擇,可以使用 <dfn>switch</dfn> 語句。 `switch` 評估一個表達式,將表達式的值與 <dfn>case</dfn> 子句匹配。 從第一個匹配的 `case` 值執行語句,直到遇到 `break`。
If you need to match one value against many options, you can use a <dfn>switch</dfn> statement. A `switch` statement compares the value to the <dfn>case</dfn> statements which define various possible values. Any valid JavaScript statements can be executed inside a <dfn>case</dfn> block and will run from the first matched `case` value until a `break` is encountered.
這是 `switch` 語句的示例:
@@ -18,7 +18,7 @@ Here is the <a href="https://colab.research.google.com/drive/1foxkSd90q1tHCSqyY6
# --question--
## --assignment--
## --作業--
Complete the problems on pages 155 and 163 from "Business Math, a Step-by-Step Handbook (2021)".
@@ -11,7 +11,7 @@ dashedName: escape-sequences-in-strings
引号不是字符串中唯一可以被转义(<dfn>escaped</dfn>)的字符。 转义字符允许你使用可能无法在字符串中使用的字符。
<table class='table table-striped'><thead><tr><th>代码</th><th>输出</th></tr></thead><tbody><tr><td><code>\'</code></td><td>单引号</td></tr><tr><td><code>\"</code></td><td>双引号</td></tr><tr><td><code>\\</code></td><td>反斜杠</td></tr><tr><td><code>\n</code></td><td>换行符</td></tr><tr><td><code>\t</code></td><td>制表符</td></tr><tr><td><code>\r</code></td><td>回车</td></tr><tr><td><code>\b</code></td><td>退格</td></tr><tr><td><code>\f</code></td><td>换页符</td></tr></tbody></table>
<table class='table table-striped'><thead><tr><th>代码</th><th>输出</th></tr></thead><tbody><tr><td><code>\'</code></td><td>单引号</td></tr><tr><td><code>\"</code></td><td>双引号</td></tr><tr><td><code>\\</code></td><td>反斜杠</td></tr><tr><td><code>\n</code></td><td>换行符</td></tr><tr><td><code>\t</code></td><td>制表符</td></tr><tr><td><code>\r</code></td><td>回车</td></tr><tr><td><code>\b</code></td><td>backspace</td></tr><tr><td><code>\f</code></td><td>换页符</td></tr></tbody></table>
*请注意,反斜线本身必须被转义,才能显示为反斜线。*
@@ -9,7 +9,7 @@ dashedName: selecting-from-many-options-with-switch-statements
# --description--
如果你有非常多的选项需要选择,可以使用 <dfn>switch</dfn> 语句。 `switch` 评估一个表达式,将表达式的值与 <dfn>case</dfn> 子句匹配。 从第一个匹配的 `case` 值执行语句,直到遇到 `break`。
If you need to match one value against many options, you can use a <dfn>switch</dfn> statement. A `switch` statement compares the value to the <dfn>case</dfn> statements which define various possible values. Any valid JavaScript statements can be executed inside a <dfn>case</dfn> block and will run from the first matched `case` value until a `break` is encountered.
这是 `switch` 语句的示例:
@@ -18,7 +18,7 @@ Here is the <a href="https://colab.research.google.com/drive/1foxkSd90q1tHCSqyY6
# --question--
## --assignment--
## --作业--
Complete the problems on pages 155 and 163 from "Business Math, a Step-by-Step Handbook (2021)".
@@ -11,7 +11,7 @@ dashedName: escape-sequences-in-strings
Las comillas no son los únicos caracteres que pueden ser <dfn>escapados</dfn> dentro de una cadena. Las secuencias de escape le permiten utilizar caracteres que de otro modo no podrías usar en una cadena.
<table class='table table-striped'><thead><tr><th>Código</th><th>Resultado</th></tr></thead><tbody><tr><td><code>\'</code></td><td>comilla simple</td></tr><tr><td><code>\"</code></td><td>comilla doble</td></tr><tr><td><code>\\</code></td><td>barra invertida</td></tr><tr><td><code>\n</code></td><td>línea nueva</td></tr><tr><td><code>\t</code></td><td>tabulador</td></tr><tr><td><code>\r</code></td><td>retorno del carro</td></tr><tr><td><code>\b</code></td><td>límite de palabra</td></tr><tr><td><code>\f</code></td><td>fuente de formulario</td></tr></tbody></table>
<table class='table table-striped'><thead><tr><th>Código</th><th>Resultado</th></tr></thead><tbody><tr><td><code>\'</code></td><td>comilla simple</td></tr><tr><td><code>\"</code></td><td>comilla doble</td></tr><tr><td><code>\\</code></td><td>barra invertida</td></tr><tr><td><code>\n</code></td><td>línea nueva</td></tr><tr><td><code>\t</code></td><td>tabulador</td></tr><tr><td><code>\r</code></td><td>retorno del carro</td></tr><tr><td><code>\b</code></td><td>backspace</td></tr><tr><td><code>\f</code></td><td>fuente de formulario</td></tr></tbody></table>
*Ten en cuenta que la barra invertida debe escaparse para que aparezca como tal.*
@@ -9,7 +9,7 @@ dashedName: selecting-from-many-options-with-switch-statements
# --description--
Si tienes muchas opciones para elegir, usa una declaración <dfn>switch</dfn>. Una sentencia `switch` prueba un valor y puede tener muchas sentencias <dfn>case</dfn> que definen varios valores posibles. Las sentencias se ejecutan desde el primer valor `case` coincidente hasta que se encuentra un `break`.
If you need to match one value against many options, you can use a <dfn>switch</dfn> statement. A `switch` statement compares the value to the <dfn>case</dfn> statements which define various possible values. Any valid JavaScript statements can be executed inside a <dfn>case</dfn> block and will run from the first matched `case` value until a `break` is encountered.
Aquí hay un ejemplo de una declaración `switch`:
@@ -11,7 +11,7 @@ dashedName: escape-sequences-in-strings
Anführungszeichen sind nicht die einzigen Zeichen, die innerhalb eines Strings <dfn>ausgelassen</dfn> werden können. Escape-Sequenzen ermöglichen es dir, Zeichen zu verwenden, die du sonst nicht in einem String verwenden könntest.
<table class='table table-striped'><thead><tr><th>Code</th><th>Ausgabe</th></tr></thead><tbody><tr><td><code>\'</code></td><td>Einzelnes Anführungszeichen</td></tr><tr><td><code>\"</code></td><td>Doppeltes Anführungszeichen</td></tr><tr><td><code>\\</code></td><td>Backslash</td></tr><tr><td><code>\n</code></td><td>Zeilenumbruch</td></tr><tr><td><code>\t</code></td><td>Tabulator</td></tr><tr><td><code>\r</code></td><td>Wagenrücklauf (Carriage Return)</td></tr><tr><td><code>\b</code></td><td>Backspace</td></tr><tr><td><code>\f</code></td><td>Seitenvorschub (Formfeed)</td></tr></tbody></table>
<table class='table table-striped'><thead><tr><th>Code</th><th>Ausgabe</th></tr></thead><tbody><tr><td><code>\'</code></td><td>Einzelnes Anführungszeichen</td></tr><tr><td><code>\"</code></td><td>Doppeltes Anführungszeichen</td></tr><tr><td><code>\\</code></td><td>Backslash</td></tr><tr><td><code>\n</code></td><td>Zeilenumbruch</td></tr><tr><td><code>\t</code></td><td>Tabulator</td></tr><tr><td><code>\r</code></td><td>Wagenrücklauf (Carriage Return)</td></tr><tr><td><code>\b</code></td><td>backspace</td></tr><tr><td><code>\f</code></td><td>Seitenvorschub (Formfeed)</td></tr></tbody></table>
*Note that the backslash itself must be escaped in order to display as a backslash.*
@@ -9,7 +9,7 @@ dashedName: selecting-from-many-options-with-switch-statements
# --description--
Wenn du viele Optionen zur Auswahl hast, verwende eine <dfn>switch</dfn>-Anweisung. Eine `switch`-Anweisung testet einen Wert und kann viele <dfn>case</dfn>-Anweisungen haben, die verschiedene mögliche Werte definieren. Die Anweisungen werden ab dem ersten übereinstimmenden `case`-Wert ausgeführt, bis ein `break` auftritt.
If you need to match one value against many options, you can use a <dfn>switch</dfn> statement. A `switch` statement compares the value to the <dfn>case</dfn> statements which define various possible values. Any valid JavaScript statements can be executed inside a <dfn>case</dfn> block and will run from the first matched `case` value until a `break` is encountered.
Hier ist ein Beispiel für eine `switch`-Anweisung:
@@ -11,7 +11,7 @@ dashedName: escape-sequences-in-strings
Le virgolette non sono gli unici caratteri dei quali si può fare l'<dfn>escaping</dfn> all'interno di una stringa. Le sequenze di escape ti permettono di usare caratteri che altrimenti non saresti in grado di usare in una stringa.
<table class='table table-striped'><thead><tr><th>Codice</th><th>Output</th></tr></thead><tbody><tr><td><code>\'</code></td><td>virgoletta singola</td></tr><tr><td><code>\"</code></td><td>doppia citazione</td></tr><tr><td><code>\\</code></td><td>barra rovesciata</td></tr><tr><td><code>\n</code></td><td>nuova riga</td></tr><tr><td><code>\t</code></td><td>tabulazione</td></tr><tr><td><code>\r</code></td><td>ritorno a capo</td></tr><tr><td><code>\b</code></td><td>delimitatore di parola</td></tr><tr><td><code>\f</code></td><td>avanzamento carta (form feed)</td></tr></tbody></table>
<table class='table table-striped'><thead><tr><th>Codice</th><th>Output</th></tr></thead><tbody><tr><td><code>\'</code></td><td>virgoletta singola</td></tr><tr><td><code>\"</code></td><td>doppia citazione</td></tr><tr><td><code>\\</code></td><td>barra rovesciata</td></tr><tr><td><code>\n</code></td><td>nuova riga</td></tr><tr><td><code>\t</code></td><td>tabulazione</td></tr><tr><td><code>\r</code></td><td>ritorno a capo</td></tr><tr><td><code>\b</code></td><td>backspace</td></tr><tr><td><code>\f</code></td><td>avanzamento carta (form feed)</td></tr></tbody></table>
*Nota che la barra rovesciata necessita di escaping perché appaia come una barra rovesciata.*
@@ -9,7 +9,7 @@ dashedName: selecting-from-many-options-with-switch-statements
# --description--
Se hai molte opzioni tra cui scegliere, usa un'istruzione <dfn>switch</dfn>. Un'istruzione `switch` verifica un valore e può avere molte istruzioni <dfn>case</dfn> che definiscono vari valori possibili. Le istruzioni vengono eseguite dal primo valore `case` che combacia e fino a quando non si incontra un `break`.
If you need to match one value against many options, you can use a <dfn>switch</dfn> statement. A `switch` statement compares the value to the <dfn>case</dfn> statements which define various possible values. Any valid JavaScript statements can be executed inside a <dfn>case</dfn> block and will run from the first matched `case` value until a `break` is encountered.
Ecco un esempio di un'istruzione `switch`:
@@ -7,7 +7,7 @@ dashedName: step-9
# --description--
That is as far as you can get with the calculate function for now. It is time to write your mean logic.
Questo è tutto quello che puoi fare per ora con la funzione calculate. È ora di scrivere la logica per la media.
Crea una funzione vuota chiamata `getMean`. Dovrebbe prendere un singolo parametro `array`.
@@ -7,7 +7,7 @@ dashedName: step-31
# --description--
Se più numeri in una serie si presentano con la stessa frequenza più alta, sono tutti considerati la moda. Otherwise, the mode is the number that occurs most often, that single number is the mode.
Se più numeri in una serie si presentano con la stessa frequenza più alta, sono tutti considerati la moda. Altrimenti, la moda è il numero che si verifica più spesso, quel singolo numero è la moda.
Per fortuna, è possibile gestire entrambi questi casi contemporaneamente con il metodo `.filter()`. Inizia dichiarando una variabile `mode` e assegnandole il valore di `Object.keys(counts)`.
@@ -7,23 +7,23 @@ dashedName: step-59
# --description--
You also need to confirm the input is valid. Declare an `invalidInputMatch` variable, and assign it the result of calling your `isInvalidInput` function with `currVal` as the argument.
Devi anche confermare che l'input sia valido. Dichiara una variabile `invalidInputMatch` e assegnale il risultato della chiamata della funzione `isInvalidInput` con `currVal` come argomento.
# --hints--
You should declare an `invalidInputMatch` variable.
Dovresti dichiarare una variabile `invalidInputMatch`.
```js
assert.match(getCaloriesFromInputs.toString(), /invalidInputMatch\s*=/);
```
You should assign the result of calling `isInvalidInput` to your `invalidInputMatch` variable.
Dovresti assegnare il risultato della chiamata di `isInvalidInput` alla variabile `invalidInputMatch`.
```js
assert.match(getCaloriesFromInputs.toString(), /invalidInputMatch\s*=\s*isInvalidInput\(/);
```
You should pass `currVal` as the parameter to `isInvalidInput`.
Dovresti passare `currVal` come parametro a `isInvalidInput`.
```js
assert.match(getCaloriesFromInputs.toString(), /invalidInputMatch\s*=\s*isInvalidInput\(\s*currVal\s*\)/);
@@ -7,11 +7,11 @@ dashedName: step-60
# --description--
Remember that your `isInvalidInput` function returns `String.match`, which is an array of matches or `null` if no matches are found.
Ricorda che la funzione `isInvalidInput` restituisce `String.match`, che è un array con le corrispondenze o `null` se non viene trovato riscontro.
In JavaScript, values can either be <dfn>truthy</dfn> or <dfn>falsy</dfn>. A value is truthy if it evaluates to `true` when converted to a Boolean. A value is falsy if it evaluates to `false` when converted to a Boolean. `null` is an example of a falsy value.
In JavaScript, i valori possono essere <dfn>truthy</dfn> o <dfn>falsy</dfn>. Un valore è truthy se viene valutato come `true` quando convertito in un booleano. Un valore è falsy se viene valutato come `false` quando convertito in un booleano. `null` è un esempio di valore falsy.
You need to check if `invalidInputMatch` is truthy – you can do this by passing the variable directly to your `if` condition (without a comparison operator). Here's an example of checking the truthiness of `helloWorld`.
Devi controllare se `invalidInputMatch` è truthy – puoi farlo passando la variabile direttamente alla condizione di `if` (senza operatore di confronto). Ecco un esempio di come verificare se `helloWorld` è truthy.
```js
if (helloWorld) {
@@ -19,23 +19,23 @@ if (helloWorld) {
}
```
Add an `if` statement that checks if `invalidInputMatch` is truthy.
Aggiungi un'istruzione `if` che controlla se `invalidInputMatch` è truthy.
# --hints--
You should add an `if` statement to your `getCaloriesFromInputs` function.
Dovresti aggiungere un'istruzione `if` alla funzione `getCaloriesFromInputs`.
```js
assert.match(getCaloriesFromInputs.toString(), /if\s*\(/);
```
You should check the truthiness of `invalidInputMatch` in your `if` condition.
Dovresti controllare se `invalidInputMatch` è truthy nella condizione di `if`.
```js
assert.match(getCaloriesFromInputs.toString(), /if\s*\(\s*invalidInputMatch\s*\)/);
```
Your `if` statement should be inside your `for` loop.
L'istruzione `if` dovrebbe trovarsi nel loop `for`.
```js
assert.isBelow(getCaloriesFromInputs.toString().indexOf("for"), getCaloriesFromInputs.toString().indexOf("if"));
@@ -7,26 +7,26 @@ dashedName: step-61
# --description--
Browsers have a built in `alert()` function, which you can use to display a pop-up message to the user. The message to display is passed as the argument to the `alert()` function.
I browser hanno una funzione `alert()` integrata che puoi usare per visualizzare un messaggio pop-up per l'utente. Il messaggio da visualizzare viene passato come argomento alla funzione `alert()`.
Using a template literal, in your `if` block, call the `alert()` function to tell the user `Invalid Input:`, followed by the first value in the `invalidInputMatch` array.
Usando un template literal nel blocco `if`, chiama la funzione `alert()` per dire all'utente `Invalid Input:`, seguito dal primo valore nell'array `invalidInputMatch`.
# --hints--
You should call the `alert()` function in your `if` block.
Dovresti chiamare la funzione `alert()` nel blocco `if`.
```js
assert.match(getCaloriesFromInputs.toString(), /if\s*\(\s*invalidInputMatch\s*\)\s*\{\s*alert\(/);
```
You should use a template literal to pass the `Invalid Input:` message to the `alert()` function.
Dovresti usare un template literal per passare il messaggio `Invalid Input:` alla funzione `alert()`.
```js
// because it transforms template literals...
assert.match(code.split("function getCaloriesFromInputs")[1], /alert\(`Invalid Input: /);
```
You should use template literal syntax to display the first value in the `invalidInputMatch` array after the `Invalid Input:` text.
Dovresti usare la sintassi di un template literal per visualizzare il primo valore nell'array `invalidInputMatch` dopo il testo `Invalid Input:`.
```js
assert.match(code.split("function getCaloriesFromInputs")[1], /alert\(`Invalid Input: \${invalidInputMatch\[0\]}`\s*\)/);
@@ -7,17 +7,17 @@ dashedName: step-62
# --description--
Still within your `if` block, set `isError` to `true` and return `null`.
Sempre all'interno del blocco `if` imposta `isError` su `true` e restituisci `null`.
# --hints--
After your `alert`, you should set `isError` to `true`.
Dopo `alert`, dovresti impostare `isError` su `true`.
```js
assert.match(code.split("function getCaloriesFromInputs")[1], /alert\(`Invalid Input: \${invalidInputMatch\[0\]}`\s*\);\s*isError\s*=\s*true/);
```
After you modify `isError`, you should `return` the value `null`.
Dopo aver modificato `isError`, dovresti usare `return` per restituire il valore `null`.
```js
assert.match(code.split("function getCaloriesFromInputs")[1], /alert\(`Invalid Input: \${invalidInputMatch\[0\]}`\s*\);\s*isError\s*=\s*true;?\s*return\s+null;?\s*\}/);
@@ -7,31 +7,31 @@ dashedName: step-63
# --description--
Remember that `return` ends the execution of a function. After your `if` block, you need to handle the logic for when the input is valid. Because your `if` statement returns a value, you do not need an `else` statement.
Ricorda che `return` termina l'esecuzione di una funzione. Dopo il blocco `if`, devi gestire la logica nel caso in cui l'input sia valido. Poiché l'istruzione `if` restituisce un valore, non hai bisogno di un'istruzione `else`.
Use the addition assignment operator to add `currVal` to your `calories` total. You'll need to use the `Number` constructor to convert `currVal` to a number.
Usa l'operatore di assegnazione composta per aggiungere `currVal` al totale `calories`. Dovrai usare il costruttore `Number` per convertire `currVal` in un numero.
# --hints--
You should not add an `else` statement.
Non dovresti aggiungere un'istruzione `else`.
```js
assert.notMatch(getCaloriesFromInputs.toString(), /else/);
```
After your `if` statement, you should use the addition assignment operator on `calories`.
Dopo l'istruzione `if` dovresti usare l'operatore di assegnazione composta su `calories`.
```js
assert.match(getCaloriesFromInputs.toString(), /if.*}\s*calories\s*\+=/s);
```
You should pass `currVal` to the `Number()` constructor.
Dovresti passare `currVal` al costruttore `Number()`.
```js
assert.match(getCaloriesFromInputs.toString(), /Number\(\s*currVal\s*\)/);
```
You should add the value of `Number(currVal)` to `calories`.
Dovresti aggiungere il valore di `Number(currVal)` a `calories`.
```js
assert.match(getCaloriesFromInputs.toString(), /calories\s*\+=\s*Number\(\s*currVal\s*\)/);
@@ -7,17 +7,17 @@ dashedName: step-64
# --description--
After your `for` loop has completed, return the `calories` value.
Una volta che il loop `for` è terminato, restituisci il valore di `calories`.
# --hints--
You should `return` the `calories` value.
Dovresti usare `return` per restituire il valore di `calories`.
```js
assert.match(getCaloriesFromInputs.toString(), /return\s+calories/);
```
Your new `return` statement should come after your `for` loop.
La nuova istruzione `return` dovrebbe trovarsi dopo il loop `for`.
```js
assert.match(getCaloriesFromInputs.toString(), /calories\s*\+=\sNumber\(currVal\);\n\s*}\n\s*return\s+calories/)
@@ -7,23 +7,23 @@ dashedName: step-65
# --description--
Now it's time to start putting it all together. Declare an empty `calculateCalories` function, which takes a parameter named `e`. This function will be another event listener, so the first argument passed will be the browser event – `e` is a common name for this parameter.
Ora è il momento di iniziare a mettere tutto insieme. Dichiara una funzione vuota `calculateCalories`, che prende un parametro chiamato `e`. Questa funzione sarà un altro event listener, quindi il primo argomento passato sarà l'evento del browser – `e` è un nome comune per questo parametro.
# --hints--
You should declare a `calculateCalories` variable.
Dovresti dichiarare una variabile `calculateCalories`.
```js
assert.isDefined(calculateCalories);
```
Your `calculateCalories` variable should be a function.
La variabile `calculateCalories` dovrebbe essere una funzione.
```js
assert.isFunction(calculateCalories);
```
Your `calculateCalories` function should take an `e` argument.
La funzione `calculateCalories` dovrebbe prendere un argomento `e`.
```js
assert.match(calculateCalories?.toString(), /\(e\)/);
@@ -7,19 +7,19 @@ dashedName: step-66
# --description--
You will be attaching this function to the `submit` event of the form. The `submit` event is triggered when the form is submitted. The default action of the `submit` event is to reload the page. You need to prevent this default action using the `preventDefault()` method of your `e` parameter.
Collegherai questa funzione all'evento `submit` del modulo. L'evento `submit` viene attivato quando il modulo viene inviato. L'azione predefinita dell'evento `submit` è ricaricare la pagina. Devi evitare questa azione predefinita usando il metodo `preventDefault()` del parametro `e`.
Add a line to your `calculateCalories` function that calls the `preventDefault()` method on the `e` parameter. Then, reset your global error flag to `false`.
Aggiungi una riga alla funzione `calculateCalories` che chiama il metodo `preventDefault()` sul parametro `e`. Quindi, reimposta il flag di errore globale su `false`.
# --hints--
Your `calculateCalories` function should call `e.preventDefault()`.
La funzione `calculateCalories` dovrebbe chiamare `e.preventDefault()`.
```js
assert.match(calculateCalories.toString(), /e\.preventDefault\(\)/);
```
Your `calculateCalories` function should reset the global error flag to `false`.
La funzione `calculateCalories` dovrebbe reimpostare il flag di errore globale su `false`.
```js
assert.match(calculateCalories.toString(), /isError\s*=\s*false/);
@@ -7,25 +7,25 @@ dashedName: step-67
# --description--
Your function needs to get the values from the entries the user has added.
La funzione deve ottenere i valori dalle voci che l'utente ha aggiunto.
Declare a `breakfastNumberInputs` variable, and give it the value of calling `document.querySelectorAll()` with the selector `#breakfast input[type=number]`. This will return any `number` inputs that are in the `#breakfast` element.
Dichiara una variabile `breakfastNumberInputs` e dalle il valore della chiamata di `document.querySelectorAll()` con il selettore `#breakfast input[type=number]`. Restituirà qualsiasi input di tipo `number` presente nell'elemento `#breakfast`.
# --hints--
You should declare a `breakfastNumberInputs` variable.
Dovresti dichiarare una variabile `breakfastNumberInputs`.
```js
assert.match(calculateCalories.toString(), /breakfastNumberInputs\s*=/);
```
You should call `document.querySelectorAll()` with `#breakfast input[type=number]`.
Dovresti chiamare `document.querySelectorAll()` con `#breakfast input[type=number]`.
```js
assert.match(calculateCalories.toString(), /document\.querySelectorAll\(('|")#breakfast input\[type=number\]\1\)/);
```
You should assign the result of your `odocument.querySelectorAll()` call to `breakfastNumberInputs`.
Dovresti assegnare il risultato della chiamata di `document.querySelectorAll()` a `breakfastNumberInputs`.
```js
assert.match(calculateCalories.toString(), /breakfastNumberInputs\s*=\s*document\.querySelectorAll\(('|")#breakfast input\[type=number\]\1\)/);
@@ -7,23 +7,23 @@ dashedName: step-68
# --description--
Using that same syntax, query your `number` inputs in the `#lunch` element and assign them to `lunchNumberInputs`.
Usando la stessa sintassi, seleziona gli input di tipo `number` nell'elemento `#lunch` e assegnali a `lunchNumberInputs`.
# --hints--
You should declare a `lunchNumberInputs` variable.
Dovresti dichiarare una variabile `lunchNumberInputs`.
```js
assert.match(calculateCalories.toString(), /lunchNumberInputs\s*=/);
```
You should call `document.querySelectorAll()` with `#lunch input[type=number]`.
Dovresti chiamare `document.querySelectorAll()` con `#lunch input[type=number]`.
```js
assert.match(calculateCalories.toString(), /document\.querySelectorAll\(('|")#lunch input\[type=number\]\1\)/);
```
You should assign the result of your `document.querySelectorAll()` call to `lunchNumberInputs`.
Dovresti assegnare il risultato della chiamata di `document.querySelectorAll()` a `lunchNumberInputs`.
```js
assert.match(calculateCalories.toString(), /lunchNumberInputs\s*=\s*document\.querySelectorAll\(('|")#lunch input\[type=number\]\1\)/);
@@ -7,59 +7,59 @@ dashedName: step-69
# --description--
Following the same pattern, query for your `number` inputs in the `#dinner`, `#snacks`, and `#exercise` elements. Assign them to variables following the naming scheme of the previous two.
Seguendo lo stesso modello, seleziona gli input di tipo `number` negli elementi `#dinner`, `#snacks` e `#exercise`. Assegnali alle variabili seguendo lo schema di denominazione delle precedenti due.
# --hints--
You should declare a `dinnerNumberInputs` variable.
Dovresti dichiarare una variabile `dinnerNumberInputs`.
```js
assert.match(calculateCalories.toString(), /dinnerNumberInputs\s*=/);
```
You should call `document.querySelectorAll()` with `#dinner input[type=number]`.
Dovresti chiamare `document.querySelectorAll()` con `#dinner input[type=number]`.
```js
assert.match(calculateCalories.toString(), /document\.querySelectorAll\(('|")#dinner input\[type=number\]\1\)/);
```
You should assign the result of your `document.querySelectorAll()` call to `dinnerNumberInputs`.
Dovresti assegnare il risultato della chiamata di `document.querySelectorAll()` a `dinnerNumberInputs`.
```js
assert.match(calculateCalories.toString(), /dinnerNumberInputs\s*=\s*document\.querySelectorAll\(('|")#dinner input\[type=number\]\1\)/);
```
You should declare a `snacksNumberInputs` variable.
Dovresti dichiarare una variabile `snacksNumberInputs`.
```js
assert.match(calculateCalories.toString(), /snacksNumberInputs\s*=/);
```
You should call `document.querySelectorAll()` with `#snacks input[type=number]`.
Dovresti chiamare `document.querySelectorAll()` con `#snacks input[type=number]`.
```js
assert.match(calculateCalories.toString(), /document\.querySelectorAll\(('|")#snacks input\[type=number\]\1\)/);
```
You should assign the result of your `document.querySelectorAll()` call to `snacksNumberInputs`.
Dovresti assegnare il risultato della chiamata di `document.querySelectorAll()` a `snacksNumberInputs`.
```js
assert.match(calculateCalories.toString(), /snacksNumberInputs\s*=\s*document\.querySelectorAll\(('|")#snacks input\[type=number\]\1\)/);
```
You should declare a `exerciseNumberInputs` variable.
Dovresti dichiarare una variabile `exerciseNumberInputs`.
```js
assert.match(calculateCalories.toString(), /exerciseNumberInputs\s*=/);
```
You should call `document.querySelectorAll()` with `#exercise input[type=number]`.
Dovresti chiamare `document.querySelectorAll()` con `#exercise input[type=number]`.
```js
assert.match(calculateCalories.toString(), /document\.querySelectorAll\(('|")#exercise input\[type=number\]\1\)/);
```
You should assign the result of your `document.querySelectorAll()` call to `exerciseNumberInputs`.
Dovresti assegnare il risultato della chiamata di `document.querySelectorAll()` a `exerciseNumberInputs`.
```js
assert.match(calculateCalories.toString(), /exerciseNumberInputs\s*=\s*document\.querySelectorAll\(('|")#exercise input\[type=number\]\1\)/);
@@ -7,25 +7,25 @@ dashedName: step-70
# --description--
Now that you have your lists of elements, you can pass them to your `getCaloriesFromInputs` function to extract the calorie total.
Ora che hai le liste di elementi, puoi passarle alla funzione `getCaloriesFromInputs` per estrarre il totale di calorie.
Declare a `breakfastCalories` variable, and assign it the result of calling `getCaloriesFromInputs` with `breakfastNumberInputs` as the argument.
Dichiara una variabile `breakfastCalories` e assegnale il risultato della chiamata di `getCaloriesFromInputs` con `breakfastNumberInputs` come argomento.
# --hints--
Your `calculateCalories` function should have a `breakfastCalories` variable.
La funzione `calculateCalories` dovrebbe avere una variabile `breakfastCalories`.
```js
assert.match(calculateCalories.toString(), /breakfastCalories\s*=/);
```
You should call `getCaloriesFromInputs` with `breakfastNumberInputs` as the argument.
Dovresti chiamare `getCaloriesFromInputs` con `breakfastNumberInputs` come argomento.
```js
assert.match(calculateCalories.toString(), /getCaloriesFromInputs\s*\(\s*breakfastNumberInputs\s*\)/);
```
You should assign the result of `getCaloriesFromInputs` to `breakfastCalories`.
Dovresti assegnare il risultato di `getCaloriesFromInputs` a `breakfastCalories`.
```js
assert.match(calculateCalories.toString(), /breakfastCalories\s*=\s*getCaloriesFromInputs\s*\(\s*breakfastNumberInputs\s*\)/);
@@ -7,23 +7,23 @@ dashedName: step-71
# --description--
Now declare a `lunchCalories` variable, and give it the value of calling `getCaloriesFromInputs` with your `lunchNumberInputs`.
Adesso dichiara la variabile `lunchCalories` e dalle il valore della chiamata di `getCaloriesFromInputs` con `lunchNumberInputs`.
# --hints--
Your `calculateCalories` function should have a `lunchCalories` variable.
La funzione `calculateCalories` dovrebbe avere una variabile `lunchCalories`.
```js
assert.match(calculateCalories.toString(), /lunchCalories\s*=/);
```
You should call `getCaloriesFromInputs` with `lunchNumberInputs` as the argument.
Dovresti chiamare `getCaloriesFromInputs` con `lunchNumberInputs` come argomento.
```js
assert.match(calculateCalories.toString(), /getCaloriesFromInputs\s*\(\s*lunchNumberInputs\s*\)/);
```
You should assign the result of `getCaloriesFromInputs` to `lunchCalories`.
Dovresti assegnare il risultato di `getCaloriesFromInputs` a `lunchCalories`.
```js
assert.match(calculateCalories.toString(), /lunchCalories\s*=\s*getCaloriesFromInputs\s*\(\s*lunchNumberInputs\s*\)/);
@@ -7,59 +7,59 @@ dashedName: step-72
# --description--
Following this same pattern, declare variables for the `number` inputs in the `#dinner`, `#snacks`, and `#exercise` elements. Assign them the appropriate `getCaloriesFromInputs` calls.
Seguendo questo stesso modello, dichiara le variabili per gli input di tipo `number` negli elementi `#dinner`, `#snacks` e `#exercise`. Assegna loro le chiamate `getCaloriesFromInputs` appropriate.
# --hints--
Your `calculateCalories` function should have a `dinnerCalories` variable.
La funzione `calculateCalories` dovrebbe avere una variabile `dinnerCalories`.
```js
assert.match(calculateCalories.toString(), /dinnerCalories\s*=/);
```
You should call `getCaloriesFromInputs` with `dinnerNumberInputs` as the argument.
Dovresti chiamare `getCaloriesFromInputs` con `dinnerNumberInputs` come argomento.
```js
assert.match(calculateCalories.toString(), /getCaloriesFromInputs\s*\(\s*dinnerNumberInputs\s*\)/);
```
You should assign the result of `getCaloriesFromInputs` to `dinnerCalories`.
Dovresti assegnare il risultato di `getCaloriesFromInputs` a `dinnerCalories`.
```js
assert.match(calculateCalories.toString(), /dinnerCalories\s*=\s*getCaloriesFromInputs\s*\(\s*dinnerNumberInputs\s*\)/);
```
Your `calculateCalories` function should have a `snacksCalories` variable.
La funzione `calculateCalories` dovrebbe avere una variabile `snacksCalories`.
```js
assert.match(calculateCalories.toString(), /snacksCalories\s*=/);
```
You should call `getCaloriesFromInputs` with `snacksNumberInputs` as the argument.
Dovresti chiamare `getCaloriesFromInputs` con `snacksNumberInputs` come argomento.
```js
assert.match(calculateCalories.toString(), /getCaloriesFromInputs\s*\(\s*snacksNumberInputs\s*\)/);
```
You should assign the result of `getCaloriesFromInputs` to `snacksCalories`.
Dovresti assegnare il risultato di `getCaloriesFromInputs` a `snacksCalories`.
```js
assert.match(calculateCalories.toString(), /snacksCalories\s*=\s*getCaloriesFromInputs\s*\(\s*snacksNumberInputs\s*\)/);
```
Your `calculateCalories` function should have a `exerciseCalories` variable.
La funzione `calculateCalories` dovrebbe avere una variabile `exerciseCalories`.
```js
assert.match(calculateCalories.toString(), /exerciseCalories\s*=/);
```
You should call `getCaloriesFromInputs` with `exerciseNumberInputs` as the argument.
Dovresti chiamare `getCaloriesFromInputs` con `exerciseNumberInputs` come argomento.
```js
assert.match(calculateCalories.toString(), /getCaloriesFromInputs\s*\(\s*exerciseNumberInputs\s*\)/);
```
You should assign the result of `getCaloriesFromInputs` to `exerciseCalories`.
Dovresti assegnare il risultato di `getCaloriesFromInputs` a `exerciseCalories`.
```js
assert.match(calculateCalories.toString(), /exerciseCalories\s*=\s*getCaloriesFromInputs\s*\(\s*exerciseNumberInputs\s*\)/);
@@ -7,27 +7,27 @@ dashedName: step-73
# --description--
You also need to get the value of your `#budget` input. You already queried this at the top of your code, and set it to the `budgetNumberInput` variable. However, you used `getElementById`, which returns an `Element`, not a `NodeList`.
Devi anche ottenere il valore dell'input `#budget`. Lo hai già selezionato in cima al codice e impostato sulla variabile `budgetNumberInput`. Tuttavia, hai usato `getElementById`, che restituisce un `Element`, non un `NodeList`.
A `NodeList` is an array-like, which means you can iterate through it and it shares some common methods with an array. For your `getCaloriesFromInputs` function, an array will work for the argument just as well as a `NodeList` does.
Un `NodeList` è un oggetto array-like, il che vuol dire che è iterabile e condivide alcuni metodi con gli array. Per la funzione `getCaloriesFromInputs` un array andrà bene come argomento proprio come un `NodeList`.
Declare a `budgetCalories` variable and set it to the result of calling `getCaloriesFromInputs` – pass an array containing your `budgetNumberInput` as the argument.
Dichiara una variabile `budgetCalories` e impostala sul risultato della chiamata di `getCaloriesFromInputs` – passa un array contenente `budgetNumberInput` come argomento.
# --hints--
Your `calculateCalories` function should have a `budgetCalories` variable.
La funzione `calculateCalories` dovrebbe avere una variabile `budgetCalories`.
```js
assert.match(calculateCalories.toString(), /budgetCalories\s*=/);
```
You should call `getCaloriesFromInputs` with `[budgetNumberInput]` as the argument.
Dovresti chiamare `getCaloriesFromInputs` con `[budgetNumberInput]` come argomento.
```js
assert.match(calculateCalories.toString(), /getCaloriesFromInputs\s*\(\s*\[\s*budgetNumberInput\s*\]\s*\)/);
```
You should assign the result of `getCaloriesFromInputs` to `budgetCalories`.
Dovresti assegnare il risultato di `getCaloriesFromInputs` a `budgetCalories`.
```js
assert.match(calculateCalories.toString(), /budgetCalories\s*=\s*getCaloriesFromInputs\s*\(\s*\[\s*budgetNumberInput\s*\]\s*\)/);
@@ -7,23 +7,23 @@ dashedName: step-74
# --description--
Your `getCaloriesFromInputs` function will set the global error flag to `true` if an invalid input is detected. Add an `if` statement to your `calculateCalories` function that checks the truthiness of your global error flag, and if it is truthy then use `return` to end the function execution.
La funzione `getCaloriesFromInputs` imposterà il flag di errore globale su `true` se viene rilevato un input non valido. Aggiungi un'istruzione `if` alla funzione `calculateCalories` che controlla se il flag di errore globale è truthy e se lo è usa `return` per terminare l'esecuzione della funzione.
# --hints--
Your `calculateCalories` function should have an `if` statement.
La funzione `calculateCalories` dovrebbe avere un'istruzione `if`.
```js
assert.match(calculateCalories.toString(), /if\s*\(/);
```
Your `if` statement should check the truthiness of the `isError` variable.
L'istruzione `if` dovrebbe verificare se la variabile `isError` è truthy.
```js
assert.match(calculateCalories.toString(), /if\s*\(\s*isError\s*\)/);
```
Your `if` statement should use `return` to end the function execution.
L'istruzione `if` dovrebbe usare `return` per terminare l'esecuzione della funzione.
```js
assert.match(calculateCalories.toString(), /if\s*\(\s*isError\s*\)\s*\{?\s*return;?\s*\}?\s*/);
@@ -7,29 +7,29 @@ dashedName: step-75
# --description--
It is time to start preparing your calculations. Start by declaring a `consumedCalories` variable, and assign it the sum of `breakfastCalories`, `lunchCalories`, `dinnerCalories`, and `snacksCalories` (note that order matters for the tests). Be sure to do this after your `if` statement.
È ora di iniziare a preparare i calcoli. Inizia dichiarando una variabile `consumedCalories` e assegnale la somma di `breakfastCalories`, `lunchCalories`, `dinnerCalories` e `snacksCalories` (l'ordine conta per i test). Assicurati di farlo dopo l'istruzione `if`.
# --hints--
Your function should have a `consumedCalories` variable.
La funzione dovrebbe avere una variabile `consumedCalories`.
```js
assert.match(calculateCalories.toString(), /consumedCalories\s*=/);
```
Your `consumedCalories` variable should come after your `if` statement.
La variabile `consumedCalories` dovrebbe trovarsi dopo l'istruzione `if`.
```js
assert.isAbove(calculateCalories.toString().indexOf('consumedCalories'), calculateCalories.toString().indexOf('if'));
```
You should calculate the sum of `breakfastCalories`, `lunchCalories`, `dinnerCalories`, and `snacksCalories`, in order.
Dovresti calcolare la somma di `breakfastCalories`, `lunchCalories`, `dinnerCalories` e `snacksCalories`, in ordine.
```js
assert.match(calculateCalories.toString(), /breakfastCalories\s*\+\s*lunchCalories\s*\+\s*dinnerCalories\s*\+\s*snacksCalories/);
```
You should assign the sum of `breakfastCalories`, `lunchCalories`, `dinnerCalories`, and `snacksCalories` to `consumedCalories`.
Dovresti assegnare la somma di `breakfastCalories`, `lunchCalories`, `dinnerCalories` e `snacksCalories` a `consumedCalories`.
```js
assert.match(calculateCalories.toString(), /consumedCalories\s*=\s*breakfastCalories\s*\+\s*lunchCalories\s*\+\s*dinnerCalories\s*\+\s*snacksCalories/);
@@ -7,23 +7,23 @@ dashedName: step-76
# --description--
Now declare a `remainingCalories` variable, and give it the value of subtracting `consumedCalories` from `budgetCalories` and adding `exerciseCalories`.
Ora dichiara una variabile `remainingCalories` e dalle il valore della sottrazione di `consumedCalories` da `budgetCalories` con l'aggiunta di `exerciseCalories`.
# --hints--
Your `calculateCalories` function should have a `remainingCalories` variable.
La funzione `calculateCalories` dovrebbe avere una variabile `remainingCalories`.
```js
assert.match(calculateCalories.toString(), /remainingCalories\s*=/);
```
You should find the value of `budgetCalories - consumedCalories + exerciseCalories`.
Dovresti trovare il valore di `budgetCalories - consumedCalories + exerciseCalories`.
```js
assert.match(calculateCalories.toString(), /budgetCalories\s*-\s*consumedCalories\s*\+\s*exerciseCalories/);
```
You should assign the value of `budgetCalories - consumedCalories + exerciseCalories` to `remainingCalories`.
Dovresti assegnare il valore di `budgetCalories - consumedCalories + exerciseCalories` a `remainingCalories`.
```js
assert.match(calculateCalories.toString(), /remainingCalories\s*=\s*budgetCalories\s*-\s*consumedCalories\s*\+\s*exerciseCalories/);
@@ -7,37 +7,37 @@ dashedName: step-77
# --description--
You need to know if the user's calories are a surplus or a deficit. Declare a `surplusOrDeficit` variable.
Devi sapere se le calorie dell'utente sono in surplus o in deficit. Dichiara una variabile `surplusOrDeficit`.
Use a ternary operator to set `surplusOrDeficit` to the string `Surplus` or `Deficit` depending on whether `remainingCalories` is greater than or equal to `0`. If it is greater than or equal to `0`, then `surplusOrDeficit` should be `Surplus`. Otherwise, it should be `Deficit`.
Usa un operatore ternario per impostare `surplusOrDeficit` sulla stringa `Surplus` o `Deficit` a seconda che `remainingCalories` sia maggiore di o uguale a `0`. Se è maggiore o uguale a `0`, allora `surplusOrDeficit` dovrebbe essere `Surplus`. Altrimenti dovrebbe essere `Deficit`.
# --hints--
Your `calculateCalories` function should have a `surplusOrDeficit` variable.
La funzione `calculateCalories` dovrebbe avere una variabile `surplusOrDeficit`.
```js
assert.match(calculateCalories.toString(), /surplusOrDeficit\s*=/g);
```
You should have a ternary operator that checks if `remainingCalories` is greater than or equal to `0`.
Dovresti avere un operatore ternario che controlla se `remainingCalories` è maggiore o uguale a `0`.
```js
assert.match(calculateCalories.toString(), /remainingCalories\s*>=\s*0\s*\?/g);
```
Your ternary operator return the string `Surplus` if `remainingCalories` is greater than or equal to `0`.
L'operatore ternario restituisce la stringa `Surplus` se `remainingCalories` è maggiore o uguale a `0`.
```js
assert.match(calculateCalories.toString(), /remainingCalories\s*>=\s*0\s*\?\s*('|")Surplus\1\s*:/g);
```
Your ternary operator return the string `Deficit` if `remainingCalories` is not greater than or equal to `0`.
L'operatore ternario restituisce la stringa `Deficit` se `remainingCalories` non è maggiore o uguale a `0`.
```js
assert.match(calculateCalories.toString(), /remainingCalories\s*>=\s*0\s*\?\s*('|")Surplus\1\s*:\s*('|")Deficit\2/g);
```
You should assign the result of your ternary operator to `surplusOrDeficit`.
Dovresti assegnare il risultato dell'operatore ternario a `surplusOrDeficit`.
```js
assert.match(calculateCalories.toString(), /surplusOrDeficit\s*=\s*remainingCalories\s*>=\s*0\s*\?\s*('|")Surplus\1\s*:\s*('|")Deficit\2/g);
@@ -7,17 +7,17 @@ dashedName: step-78
# --description--
You need to construct the HTML string that will be displayed in the `output` element. Start by assigning an empty template literal to the `innerHTML` property of the `output` element.
Devi costruire la stringa HTML che verrà visualizzata nell'elemento `output`. Inizia assegnando un template literal vuoto alla proprietà `innerHTML` dell'elemento `output`.
# --hints--
You should access the `innerHTML` property of the `output` element.
Dovresti accedere alla proprietà `innerHTML` dell'elemento `output`.
```js
assert.match(calculateCalories.toString(), /output\s*\.\s*innerHTML/);
```
You should assign an empty template literal to the `innerHTML` property of the `output` element.
Dovresti assegnare un template literal vuoto alla proprietà `innerHTML` dell'elemento `output`.
```js
// again, template literals don't play well with the parser so we have to look at the raw code.
@@ -7,34 +7,34 @@ dashedName: step-79
# --description--
Your `output.innerHTML` string will need a `span` element. Create that, and give it a `class` attribute set to the `surplusOrDeficit` variable, but lowercased.
La stringa `output.innerHTML` avrà bisogno di un elemento `span`. Crealo e dagli un attributo `class` impostato sulla variabile `surplusOrDeficit`, ma in minuscolo.
Strings have a `.toLowerCase()` method that can help you with this. Do not give your `span` any text yet.
Le stringhe hanno un metodo `.toLowerCase()` che può aiutarti in questo. Non dare ancora allo `span` alcun testo.
# --hints--
You should create a `span` element in your template literal.
Dovresti creare un elemento `span` nel template literal.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
assert.match(htmlString, /<span/);
```
Your `span` element should have a `class` attribute.
L'elemento `span` dovrebbe avere un attributo `class`.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
assert.match(htmlString, /<span\s+class\s*=/);
```
Your `span` should have the `class` attribute set to `surplusOrDeficit.toLowerCase()`.
L'elemento `span` dovrebbe avere l'attributo `class` impostato su `surplusOrDeficit.toLowerCase()`.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
assert.match(htmlString, /<span\s+class\s*=\s*"\$\{surplusOrDeficit\s*\.toLowerCase\(\s*\)\}"\s*>/);
```
Your `span` should not have any text.
L'elemento `span` non dovrebbe avere alcun testo.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
@@ -7,11 +7,11 @@ dashedName: step-80
# --description--
Give your span the text `remainingCalories Calorie surplusOrDeficit`, using interpolation to replace `remainingCalories` and `surplusOrDeficit` with the appropriate variables.
Dai allo span il testo `remainingCalories Calorie surplusOrDeficit` usando l'interpolazione per sostituire `remainingCalories` e `surplusOrDeficit` con le variabili appropriate.
# --hints--
Your `span` should have the text `${remainingCalories} Calorie ${surplusOrDeficit}`.
Lo `span` dovrebbe avere il testo `${remainingCalories} Calorie ${surplusOrDeficit}`.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
@@ -7,20 +7,20 @@ dashedName: step-81
# --description--
When the user has a calorie deficit, the `remainingCalories` value will be negative. You don't want to display a negative number in the result string.
Quando l'utente ha un deficit calorico, il valore di `remainingCalories` sarà negativo. Non vuoi mostrare un numero negativo nella stringa risultante.
`Math.abs()` is a built-in JavaScript method that will return the absolute value of a number. In your `span` text, wrap your `remainingCalories` reference in `Math.abs()` to ensure that the value is positive.
`Math.abs()` è un metodo integrato di JavaScript che restituisce il valore assoluto di un numero. Nel testo dello `span` racchiudi il riferimento a `remainingCalories` in `Math.abs()` per assicurarti che il valore sia positivo.
# --hints--
You should wrap the `remainingCalories` variable in `Math.abs()`.
Dovresti racchiudere la variabile `remainingCalories` in `Math.abs()`.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
assert.match(htmlString, /Math\.abs\(\s*remainingCalories\s*\)/);
```
Your `span` should have the text `${Math.abs(remainingCalories)} Calorie ${surplusOrDeficit}`.
Lo `span` dovrebbe avere il testo `${Math.abs(remainingCalories)} Calorie ${surplusOrDeficit}`.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
@@ -7,27 +7,27 @@ dashedName: step-82
# --description--
After your `span` element, add an `hr` element to create a horizontal line.
Dopo l'elemento `span`, aggiungi un elemento `hr` per creare una linea orizzontale.
To keep your code clean and readable, you should add this on a new line in the template literal.
Per mantenere il codice pulito e leggibile, dovresti aggiungerlo su una nuova riga nel template literal.
# --hints--
You should add an `hr` element to your `output.innerHTML` string.
Dovresti aggiungere un elemento `hr` alla stringa `output.innerHTML`.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
assert.match(htmlString, /<hr\s*\/?>/);
```
Your `hr` element should come after your `span` element.
L'elemento `hr` dovrebbe trovarsi dopo l'elemento `span`.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
assert.isAbove(htmlString.indexOf('<hr'), htmlString.indexOf('<span'));
```
Your `hr` element should be on a new line.
L'elemento `hr` dovrebbe essere su una nuova riga.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
@@ -7,34 +7,34 @@ dashedName: step-83
# --description--
Now create a `p` element with the text `budgetCalories Calories Budgeted`, using interpolation to replace `budgetCalories` with the appropriate variable.
Ora crea un elemento `p` con il testo `budgetCalories Calories Budgeted`, utilizzando l'interpolazione per sostituire `budgetCalories` con la variabile appropriata.
This should come after your `hr` element.
Dovrebbe trovarsi dopo l'elemento `hr`.
# --hints--
You should create a `p` element.
Dovresti creare un elemento `p`.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
assert.match(htmlString, /<p>/);
```
Your `p` element should come after your `hr` element.
L'elemento `p` dovrebbe trovarsi dopo l'elemento `hr`.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
assert.isAbove(htmlString.indexOf('<p'), htmlString.indexOf('<hr'));
```
Your `p` element should be on a new line.
L'elemento `p` dovrebbe essere su una nuova riga.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
assert.match(htmlString, /\n\s*<p/);
```
Your `p` element should have the text `${budgetCalories} Calories Budgeted`.
L'elemento `p` dovrebbe avere il testo `${budgetCalories} Calories Budgeted`.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
@@ -7,32 +7,32 @@ dashedName: step-84
# --description--
Using the same interpolation syntax, add a second `p` element with the text `consumedCalories Calories Consumed` and a third with the text `exerciseCalories Calories Burned`. Remember to replace your `consumedCalories` and `exerciseCalories` variables with the appropriate values.
Usando la stessa sintassi di interpolazione, aggiungi un secondo elemento `p` con il testo `consumedCalories Calories Consumed` e un terzo con il testo `exerciseCalories Calories Burned`. Ricorda di sostituire le variabili `consumedCalories` e `exerciseCalories` con i valori appropriati.
# --hints--
You should add a second `p` element to your template literal.
Dovresti aggiungere un secondo elemento `p` al template literal.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
assert.isAtLeast(htmlString.match(/<p>/g).length, 2);
```
Your second `p` element should be on a new line.
Il secondo elemento `p` dovrebbe trovarsi su una nuova riga.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
assert.match(htmlString, /\n\s*<p/)
```
Your second `p` element should come after your existing `p` element.
Il secondo elemento `p` dovrebbe trovarsi dopo l'elemento `p` esistente.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
assert(htmlString.match(/<p>\$\{budgetCalories\}\s*Calories\s*Budgeted<\/p>\n\s*<p/));
```
Your second `p` element should have the text `${consumedCalories} Calories Consumed`.
Il secondo elemento `p` dovrebbe avere il testo `${consumedCalories} Calories Consumed`.
```js
const htmlString = code.split(/output\s*\.\s*innerHTML\s*=\s*/)[1].split(/`/)[1];
@@ -7,25 +7,25 @@ dashedName: step-85
# --description--
Finally, you need to make the `#output` element visible so the user can see your text. Your `output` variable is an Element, which has a `classList` property. This property has a `.remove()` method, which accepts a string representing the class to remove from the element.
Infine, devi rendere visibile l'elemento `#output` in modo che l'utente possa vederne il testo. La variabile `output` è un elemento, che ha una proprietà `classList`. Questa proprietà ha un metodo `.remove()`, che accetta una stringa che rappresenta la classe da rimuovere dall'elemento.
Use the `.remove()` method of the `output` variable's `classList` property to remove the `hide` class. Don't forget to place the word `hide` inside quotes.
Usa il metodo `.remove()` della proprietà `classList` della variabile `output` per rimuovere la classe `hide`. Non dimenticare di posizionare la parola `hide` tra virgolette.
# --hints--
You should access the `classList` property of the `output` element.
Dovresti accedere alla proprietà `classList` dell'elemento `output`.
```js
assert.match(calculateCalories.toString(), /output\.classList/);
```
You should call the `.remove()` method of the `classList` property.
Dovresti chiamare il metodo `.remove()` sulla proprietà `classList`.
```js
assert.match(calculateCalories.toString(), /output\.classList\.remove\(/);
```
You should pass `hide` as the argument to the `.remove()` method.
Dovresti passare `hide` come argomento al metodo `.remove()`.
```js
assert.match(calculateCalories.toString(), /output\.classList\.remove\(\s*('|")hide\1\s*\)/);
@@ -7,25 +7,25 @@ dashedName: step-86
# --description--
If you click on your `Calculate Remaining Calories` button, you'll see that nothing happens. You still need to mount the event listener.
Se clicchi sul pulsante `Calculate Remaining Calories`, vedrai che non succede nulla. Devi ancora montare l'event listener.
Add an event listener to your `calorieCounter` element. The event type should be `submit`, and the callback function should be `calculateCalories`.
Aggiungi un event listener all'elemento `calorieCounter`. Il tipo di evento dovrebbe essere `submit` e la funzione callback dovrebbe essere `calculateCalories`.
# --hints--
You should use the `.addEventListener()` method of your `calorieCounter` element.
Dovresti usare il metodo `.addEventListener()` sull'elemento `calorieCounter`.
```js
assert.match(code, /calorieCounter\.addEventListener\(/);
```
You should pass `submit` as the first argument to `.addEventListener()`.
Dovresti passare `submit` come primo argomento a `.addEventListener()`.
```js
assert.match(code, /calorieCounter\.addEventListener\(\s*('|")submit\1\s*/);
```
You should pass `calculateCalories` as the second argument to `.addEventListener()`.
Dovresti passare `calculateCalories` come secondo argomento a `.addEventListener()`.
```js
assert.match(code, /calorieCounter\.addEventListener\(\s*('|")submit\1\s*,\s*calculateCalories\s*/);
@@ -7,23 +7,23 @@ dashedName: step-87
# --description--
Your final feature to add is the ability for a user to clear the form. Start by declaring an empty function called `clearForm` – it should not take any arguments.
L'ultima funzionalità da aggiungere è la possibilità per un utente di cancellare il modulo. Inizia dichiarando una funzione vuota chiamata `clearForm` – non dovrebbe prendere alcun argomento.
# --hints--
You should declare a `clearForm` variable.
Dovresti dichiarare una variabile `clearForm`.
```js
assert.isDefined(clearForm);
```
Your `clearForm` variable should be a function.
La variabile `clearForm` dovrebbe essere una funzione.
```js
assert.isFunction(clearForm);
```
Your `clearForm` function should not take any arguments.
La funzione `clearForm` non dovrebbe prendere alcun argomento.
```js
assert.match(clearForm?.toString(), /\(\s*\)/);
@@ -7,23 +7,23 @@ dashedName: step-88
# --description--
You need to get all of the input containers. Declare an `inputContainers` variable, and assign it to the value of querying the document for all elements with the class `input-container`.
Devi selezionare tutti i contenitori di input. Dichiara una variabile `inputContainers` e assegnale il valore della query di tutti gli elementi del documento con la classe `input-container`.
# --hints--
You should declare an `inputContainers` variable in your `clearForm` function.
Dovresti dichiarare una variabile `inputContainers` nella funzione `clearForm`.
```js
assert.match(clearForm.toString(), /inputContainers\s*=/);
```
You should use the `querySelectorAll` method to get all of the elements with the class `input-container`.
Dovresti usare il metodo `querySelectorAll` per selezionare tutti gli elementi con la classe `input-container`.
```js
assert.match(clearForm.toString(), /document\.querySelectorAll\(\s*('|")\.input-container\1\s*\)/);
```
You should assign the value of the `querySelectorAll` method to the `inputContainers` variable.
Dovresti assegnare il valore del metodo `querySelectorAll` alla variabile `inputContainers`.
```js
assert.match(clearForm.toString(), /inputContainers\s*=\s*document\.querySelectorAll\(\s*('|")\.input-container\1\s*\)/);
@@ -7,19 +7,19 @@ dashedName: step-89
# --description--
Remember that `document.querySelectorAll` returns a `NodeList`, which is array-like but is not an array. However, the `Array` object has a `.from()` method that accepts an array-like and returns an array. This is helpful when you want access to more robust array methods, which you will learn about in a future project.
Ricorda che `document.querySelectorAll` restituisce un `NodeList`, che è simile a un array ma non è un array. Tuttavia, l'oggetto `Array` ha un metodo `.from()` che accetta un array-like e restituisce un array. È utile quando vuoi accedere a metodi di array più robusti, che imparerai in un progetto futuro.
Wrap your `inputContainers` query selector in `Array.from()`. Do this on the same line as your declaration.
Racchiudi il selettore `inputContainers` in `Array.from()`. Fallo sulla stessa riga della dichiarazione.
# --hints--
You should wrap your `querySelectorAll` in `Array.from()`.
Dovresti racchiudere `querySelectorAll` in `Array.from()`.
```js
assert.match(clearForm, /Array\.from\(\s*document\.querySelectorAll\(\s*('|")\.input-container*\1\s*\)\s*\)/);
```
You should assign the result of `Array.from()` to your `inputContainers` variable.
Dovresti assegnare il risultato di `Array.from()` alla variabile `inputContainers`.
```js
assert.match(clearForm, /inputContainers\s*=\s*Array\.from\(\s*document\.querySelectorAll\(\s*('|")\.input-container*\1\s*\)\s*\)/);
@@ -7,13 +7,13 @@ dashedName: step-90
# --description--
It is time for another loop. Use a `for` loop to iterate through the `inputContainers` array.
È giunto il momento di un altro loop. Usa un loop `for` per iterare sulll'array `inputContainers`.
Inside the loop, set the `innerHTML` property of the element at the current index to an empty string. This will clear all of the contents of that input container.
All'interno del loop, imposta la proprietà `innerHTML` dell'elemento all'indice corrente su una stringa vuota. Cancellerà tutti i contenuti di quel contenitore di input.
# --hints--
Your `clearForm` function should have a `for` loop.
La funzione `clearForm` dovrebbe avere un loop `for`.
```js
// loop protect injects stuff, so let's look at the raw code again
@@ -21,14 +21,14 @@ const clearForm = code.split("function clearForm()")[1];
assert.match(clearForm, /for\s*\(/);
```
Your `for` loop should iterate through the `inputContainers` array. Remember to use `i` as your iterator.
Il loop `for` dovrebbe iterare sull'array `inputContainers`. Ricorda di usare `i` come iteratore.
```js
const clearForm = code.split("function clearForm()")[1];
assert.match(clearForm, /for\s*\(\s*let\s+i\s*=\s*0\s*;\s*i\s*<\s*inputContainers\.length\s*;\s*i\s*\+\+\s*\)/);
```
Your `for` loop should set the `innerHTML` property of `inputContainers[i]` to an empty string.
Il loop `for` dovrebbe impostare la proprietà `innerHTML` di `inputContainers[i]` su una stringa vuota.
```js
const clearForm = code.split("function clearForm()")[1];
@@ -7,23 +7,23 @@ dashedName: step-91
# --description--
After your loop completes, you need to clear the `budgetNumberInput`. Set the `value` property of `budgetNumberInput` to an empty string.
Una volta che il loop è terminato, devi svuotare `budgetNumberInput`. Imposta la proprietà `value` di `budgetNumberInput` su una stringa vuota.
# --hints--
Your `clearForm` function should access the `value` property of the `budgetNumberInput` element.
La funzione `clearForm` dovrebbe accedere alla proprietà `value` dell'elemento `budgetNumberInput`.
```js
assert.match(clearForm.toString(), /budgetNumberInput\.value/);
```
Your `clearForm` function should set the `value` property of the `budgetNumberInput` element to an empty string.
La funzione `clearForm` dovrebbe impostare la proprietà `value` dell'elemento `budgetNumberInput` su una stringa vuota.
```js
assert.match(clearForm.toString(), /budgetNumberInput\.value\s*=\s*('|"|`)\1/);
```
You should modify the `budgetNumberInput` after your `for` loop.
Dovresti modificare `budgetNumberInput` dopo il loop `for`.
```js
const clearForm = code.split("function clearForm()")[1];
@@ -7,25 +7,25 @@ dashedName: step-92
# --description--
You also need to clear the `output` element's text. You can do this by setting the `innerText` property to an empty string.
Devi anche cancellare il testo dell'elemento `output`. Puoi farlo impostando la proprietà `innerText` su una stringa vuota.
The difference between `innerText` and `innerHTML` is that `innerText` will not render HTML elements, but will display the tags and content as raw text.
La differenza tra `innerText` e `innerHTML` è che `innerText` non renderizza gli elementi HTML, ma mostra i tag e il contenuto come testo grezzo.
# --hints--
Your `clearForm` function should access the `innerText` property of the `output` element.
La funzione `clearForm` dovrebbe accedere alla proprietà `innerText` dell'elemento `output`.
```js
assert.match(clearForm.toString(), /output\.innerText/);
```
Your `clearForm` function should set the `innerText` property of the `output` element to an empty string.
La funzione `clearForm` dovrebbe impostare la proprietà `innerText` dell'elemento `output` su una stringa vuota.
```js
assert.match(clearForm.toString(), /output\.innerText\s*=\s*('|"|`)\1/);
```
You should modify `output` after modifying `budgetNumberInput`.
Dovresti modificare `output` dopo aver modificato `budgetNumberInput`.
```js
assert.isAbove(clearForm.toString().indexOf('output'), clearForm.toString().indexOf('budgetNumberInput'));
@@ -7,25 +7,25 @@ dashedName: step-93
# --description--
To finish off this function, you need to restore the `hide` class to the `output` element. The `classList` property has an `.add()` method which is the opposite of the `.remove()` method. It accepts a string representing the class to add to the element.
Per terminare questa funzione, devi ripristinare la classe `hide` nell'elemento `output`. La proprietà `classList` ha un metodo `.add()` che è l'opposto del metodo `.remove()`. Accetta una stringa che rappresenta la classe da aggiungere all'elemento.
Add the `hide` class to your `output`.
Aggiungi la classe `hide` a `output`.
# --hints--
You should access the `classList` property of the `output` element.
Dovresti accedere alla proprietà `classList` dell'elemento `output`.
```js
assert.match(clearForm.toString(), /output\.classList/);
```
You should call the `.add()` method on the `classList` property of the `output` element.
Dovresti chiamare il metodo `.add()` della proprietà `classList` dell'elemento `output`.
```js
assert.match(clearForm.toString(), /output\.classList\.add/);
```
You should pass `hide` as the argument to the `.add()` method.
Dovresti passare `hide` come argomento al metodo `.add()`.
```js
assert.match(clearForm.toString(), /output\.classList\.add\(\s*('|")hide\1\s*\)/);
@@ -7,25 +7,25 @@ dashedName: step-94
# --description--
To complete this project, add an event listener to the `clearButton` button. When the button is clicked, it should call the `clearForm` function.
Per completare questo progetto, aggiungi un event listener al pulsante `clearButton`. Quando il pulsante viene cliccato, dovrebbe chiamare la funzione `clearForm`.
Congratulations! Your project is complete.
Congratulazioni! Hai completato il progetto.
# --hints--
You should add an event listener to the `clearButton` button.
Dovresti aggiungere un event listener al pulsante `clearButton`.
```js
assert.match(code, /clearButton\s*\.addEventListener\s*\(/);
```
You should pass `click` as the first argument to `.addEventListener()`.
Dovresti passare `click` come primo argomento a `.addEventListener()`.
```js
assert.match(code, /clearButton\s*\.addEventListener\s*\(\s*('|"|`)click\1\s*/);
```
You should pass `clearForm` as the second argument to `.addEventListener()`.
Dovresti passare `clearForm` come secondo argomento a `.addEventListener()`.
```js
assert.match(code, /clearButton\s*\.addEventListener\s*\(\s*('|"|`)click\1\s*,\s*clearForm\s*/);
@@ -1,6 +1,6 @@
---
id: 63d8402e39c73468b059cd43
title: "Build a Data Graph Explorer"
title: "Crea un Data Graph Explorer"
challengeType: 10
dashedName: build-a-data-graph-explorer
---
@@ -22,7 +22,7 @@ Per questa sfida, utilizzando Python dovrai creare tre giochi matematici che ese
- Generare problemi di uno e due passaggi con valori interi casuali; il giocatore deve inserire la risposta
- Utilizzare valori positivi e negativi. Per ulteriori difficoltà, rendere i numeri più grandi
- Gioco del proiettile
- Mostrare un "muro" con altezza e posizione casuali. Player has to move sliders to adjust a parabolic path to clear the wall
- Mostrare un "muro" con altezza e posizione casuali. Il giocatore deve spostare i cursori per impostare un percorso parabolico per superare il muro
- Per ulteriori difficoltà, creare un secondo livello dove i giocatori inseriscono a, b, e c senza cursori
Quando hai finito, invia l'URL al notebook Colab pubblico sul tuo Google drive.
@@ -18,15 +18,15 @@ Quali snippet di codice sono disponibili in Google Colaboratory?
## --answers--
Camera capture
Cattura da fotocamera
---
Adding form fields
Aggiunta campi di modulo
---
Importing data from Google Sheets
Importazione dati da Google Sheets
---
@@ -1,6 +1,6 @@
---
id: 6363d2899078df117ce4c407
title: "Spreadsheets and Additional Resources"
title: "Fogli di Calcolo e Altre Risorse"
challengeType: 15
videoId: JH9Uk2mi3Dc
dashedName: spreadsheets-and-additional-resources
@@ -1,6 +1,6 @@
---
id: 6363d2019078df117ce4c3fe
title: "Word Problems"
title: "Parole nei Problemi"
challengeType: 15
videoId: 3ZM3XMn1QYo
dashedName: word-problems
@@ -28,23 +28,23 @@ Completa i problemi alle pagine 304, 308 e 321 da "Algebra and Trigonometry".
## --text--
Quale delle seguenti parole chiave indica la sottrazione?
Quali delle seguenti parole chiave indicano la sottrazione?
## --answers--
plus, more, increase, up
più, aggiunta, aumento, somma
---
difference, less, decrease, down
differenza, meno, calo, diminuzione
---
of, by, factor, area, times
per, prodotto, area, fattore
---
out of, per, divided, quotient
diviso, quoziente, rapporto, su
## --video-solution--
@@ -18,7 +18,7 @@ Ecco un <a href="https://colab.research.google.com/drive/1-HWYmzKn6HmEUWMBv7G525
## --text--
In percent increase formulas, what does the "principle" refer to?
Nella formula dell'aumento percentuale, a cosa si riferisce "capitale"?
## --answers--
@@ -11,7 +11,7 @@ dashedName: escape-sequences-in-strings
文字列の中で<dfn>エスケープ</dfn>できる文字は引用符だけではありません。 エスケープシーケンスを使用すると、文字列で通常は使用できない文字を使用できます。
<table class='table table-striped'><thead><tr><th>コード</th><th>出力</th></tr></thead><tbody><tr><td><code>\'</code></td><td>シングルクォート</td></tr><tr><td><code>\"</code></td><td>ダブルクォート</td></tr><tr><td><code>\\</code></td><td>バックスラッシュ (日本語では円記号)</td></tr><tr><td><code>\n</code></td><td>改行</td></tr><tr><td><code>\t</code></td><td>タブ</td></tr><tr><td><code>\r</code></td><td>キャリッジリターン</td></tr><tr><td><code>\b</code></td><td>単語境界</td></tr><tr><td><code>\f</code></td><td>改ページ</td></tr></tbody></table>
<table class='table table-striped'><thead><tr><th>コード</th><th>出力</th></tr></thead><tbody><tr><td><code>\'</code></td><td>シングルクォート</td></tr><tr><td><code>\"</code></td><td>ダブルクォート</td></tr><tr><td><code>\\</code></td><td>バックスラッシュ (日本語では円記号)</td></tr><tr><td><code>\n</code></td><td>改行</td></tr><tr><td><code>\t</code></td><td>タブ</td></tr><tr><td><code>\r</code></td><td>キャリッジリターン</td></tr><tr><td><code>\b</code></td><td>backspace</td></tr><tr><td><code>\f</code></td><td>改ページ</td></tr></tbody></table>
*バックスラッシュ自体をバックスラッシュとして表示するためにはエスケープする必要があります。*
@@ -9,7 +9,7 @@ dashedName: selecting-from-many-options-with-switch-statements
# --description--
選択肢が多数ある場合は <dfn>switch</dfn> ステートメントを使用してください。 `switch` ステートメントは値を調べますが、多数の <dfn>case</dfn> ステートメントを記述してさまざまな値の候補を定義することができます。 条件が一致した最初の `case` 値から `break` に達するまで、ステートメントが実行されます。
If you need to match one value against many options, you can use a <dfn>switch</dfn> statement. A `switch` statement compares the value to the <dfn>case</dfn> statements which define various possible values. Any valid JavaScript statements can be executed inside a <dfn>case</dfn> block and will run from the first matched `case` value until a `break` is encountered.
次は `switch` ステートメントの例です。
@@ -11,7 +11,7 @@ dashedName: escape-sequences-in-strings
Aspas não são os únicos caracteres que podem ser <dfn>escapados</dfn> dentro de uma string. As sequências de escape permitem que você use caracteres que você não poderia usar em uma string em outras situações.
<table class='table table-striped'><thead><tr><th>Código</th><th>Saída</th></tr></thead><tbody><tr><td><code>\'</code></td><td>aspas simples</td></tr><tr><td><code>\"</code></td><td>aspas duplas</td></tr><tr><td><code>\\</code></td><td>barra invertida</td></tr><tr><td><code>\n</code></td><td>nova linha</td></tr><tr><td><code>\t</code></td><td>tab</td></tr><tr><td><code>\r</code></td><td>retorno de carro</td></tr><tr><td><code>\b</code></td><td>limite de palavra</td></tr><tr><td><code>\f</code></td><td>quebra de página</td></tr></tbody></table>
<table class='table table-striped'><thead><tr><th>Código</th><th>Saída</th></tr></thead><tbody><tr><td><code>\'</code></td><td>aspas simples</td></tr><tr><td><code>\"</code></td><td>aspas duplas</td></tr><tr><td><code>\\</code></td><td>barra invertida</td></tr><tr><td><code>\n</code></td><td>nova linha</td></tr><tr><td><code>\t</code></td><td>tab</td></tr><tr><td><code>\r</code></td><td>retorno de carro</td></tr><tr><td><code>\b</code></td><td>backspace</td></tr><tr><td><code>\f</code></td><td>quebra de página</td></tr></tbody></table>
*Note que a própria barra invertida deve ser escapada para ser exibida como uma barra invertida.*
@@ -9,7 +9,7 @@ dashedName: selecting-from-many-options-with-switch-statements
# --description--
Se você possui muitas opções pra escolher, use uma instrução <dfn>switch</dfn>. Uma instrução `switch` testa um valor e pode ter muitas instruções <dfn>case</dfn> as quais definem os diversos valores possíveis. As instruções são executadas desde o primeiro `case` correspondente até que seja encontrado um `break`.
If you need to match one value against many options, you can use a <dfn>switch</dfn> statement. A `switch` statement compares the value to the <dfn>case</dfn> statements which define various possible values. Any valid JavaScript statements can be executed inside a <dfn>case</dfn> block and will run from the first matched `case` value until a `break` is encountered.
Aqui está um exemplo de uma instrução `switch`:
@@ -1,6 +1,6 @@
---
id: 6363d23a9078df117ce4c3ff
title: "Applications of Linear Systems: Extra"
title: "Aplicações de sistemas lineares: extra"
challengeType: 15
videoId: ZtypoUnNdAY
dashedName: applications-of-linear-systems-extra
@@ -8,29 +8,29 @@ dashedName: applications-of-linear-systems-extra
# --description--
The next video contains more examples of how to set up equations and use your Colab notebook to solve them.
O próximo vídeo contém mais exemplos de como configurar equações e usar seu notebook do Colaboratory para resolvê-las.
# --question--
## --text--
How can you make use of a Colab notebook to solve practical business problems?
Como você pode utilizar um notebook do Colaboratory para resolver problemas práticos de negócios?
## --answers--
Modify the equations in the code you already wrote
Modificar as equações no código que você já escreveu
---
Copy your existing code and then modify it as necessary
Copiar seu código existente e, em seguida, modificá-lo conforme necessário
---
Write new code based on the functions you already know
Escrever um código novo baseado nas funções que você já conhece
---
All of the above
Todas as anteriores
## --video-solution--
@@ -1,6 +1,6 @@
---
id: 6363d2019078df117ce4c3fe
title: "Word Problems"
title: "Problemas com palavras"
challengeType: 15
videoId: 3ZM3XMn1QYo
dashedName: word-problems
@@ -8,9 +8,9 @@ dashedName: word-problems
# --description--
This first video will look at key words that tell you what math operation to use. Then you will see how to apply some of your code to different problems.
Este primeiro vídeo examinará as palavras-chave que dizem a você qual operação matemática usar. Então, você verá como aplicar parte do seu código para problemas diferentes.
**Here are links to the textbooks you will need to complete the assignments for this video:**
**Aqui estão os links para os livros que você precisará para concluir as atividades para este vídeo:**
\- <a href="https://lyryx.com/subjects/business/business-mathematics/" target="_blank" rel="noopener noreferrer nofollow">Business Math, a Step-by-Step Handbook (2021), de Jean-Paul Oliver</a>
@@ -1,6 +1,6 @@
---
id: 63dbd0375d93712ff177d969
title: "Business Applications of College Algebra: Extra"
title: "Aplicações de negócios com álgebra do ensino superior: extra"
challengeType: 15
videoId: 9n_ZybF0Phc
dashedName: business-applications-of-college-algebra-extra
@@ -8,29 +8,29 @@ dashedName: business-applications-of-college-algebra-extra
# --description--
This video is showing you some economics applications, and creating graphs and formulas.
Este vídeo mostra algumas aplicações econômicas e a criação de gráficos e fórmulas.
# --question--
## --text--
Which of the following is not true of supply and demand graphs?
Qual das seguintes opções não é verdadeira para os gráficos de oferta e procura?
## --answers--
The supply curve has a positive slope
A curva de oferta tem uma inclinação positiva
---
The demand curve has a negative slope
A curva de demanda tem uma inclinação negativa
---
The supply curve and demand curve will intersect
A curva de oferta e a curva de demanda se cruzarão
---
The supply curve and demand curve will always be straight lines
A curva de oferta e a curva de demanda sempre serão linhas retas
## --video-solution--
@@ -1,6 +1,6 @@
---
id: 6363d2649078df117ce4c404
title: "Demand and Revenue"
title: "Demanda e receita"
challengeType: 15
videoId: 8PIZmiMFmfk
dashedName: demand-and-revenue
@@ -8,39 +8,39 @@ dashedName: demand-and-revenue
# --description--
In this video, you will write code to develop a demand function from two points. You will see how price affects the profit graph and how all of these equations relate to each other.
Neste vídeo, você escreverá o código para desenvolver uma função de demanda a partir de dois pontos. Você verá como o preço afeta o gráfico de lucros e como todas essas equações se relacionam entre si.
Here is the <a href="https://colab.research.google.com/drive/1foxkSd90q1tHCSqyY6NFAEnMfH0nNwXe?usp=sharing" target="_blank" rel="noopener noreferrer nofollow">Colab notebook to go along with this video.</a>
Aqui está o <a href="https://colab.research.google.com/drive/1foxkSd90q1tHCSqyY6NFAEnMfH0nNwXe?usp=sharing" target="_blank" rel="noopener noreferrer nofollow">notebook do Colaboratory que acompanha este vídeo.</a>
**Here is a link to the textbook you will need to complete the assignment for this video:**
**Aqui está o link para o livro de que você precisará para concluir a atividade para este vídeo:**
\- <a href="https://lyryx.com/subjects/business/business-mathematics/" target="_blank" rel="noopener noreferrer nofollow">Business Math, a Step-by-Step Handbook (2021) by Jean-Paul Oliver</a>
\- <a href="https://lyryx.com/subjects/business/business-mathematics/" target="_blank" rel="noopener noreferrer nofollow">Business Math, a Step-by-Step Handbook (2021), de Jean-Paul Oliver</a>
# --question--
## --assignment--
Complete the problems on pages 155 and 163 from "Business Math, a Step-by-Step Handbook (2021)".
Resolva os problemas das páginas 155 e 163 do livro "Business Math, a Step-by-Step Handbook (2021)".
## --text--
Which of the following business equations is not correct?
Qual das seguintes equações de negócio não está correta?
## --answers--
Profit = Revenue - Cost
Lucro = receita - custo
---
Revenue = Price * Demand
Receita = preço * demanda
---
Cost = Fixed Expenses + Variable Expenses
Custo = despesas fixas + despesas variáveis
---
Marginal Revenue = Margins + Revenue
Renda marginal = margens + receita
## --video-solution--
@@ -8,19 +8,19 @@ dashedName: solving-for-x
# --description--
This first video will show you the essence of algebra and then how Python code does the same task in a different way.
Este primeiro vídeo mostrará a essência da álgebra e, em seguida, como o código em Python faz a mesma tarefa de uma maneira diferente.
Here is the <a href="https://colab.research.google.com/drive/11Zi77gs1FKoEqfPqYa2HtTENiWZyQAO2?usp=sharing" target="_blank" rel="noopener noreferrer nofollow">Colab notebook to go along with this video.</a> Add the code from the video to your algebra Colab notebook to see how to solve for X using Python. Then change the code if you want, test it, and compare it to paper-and-pencil solving. Remember the equation input needs to be in Python syntax.
Aqui está o <a href="https://colab.research.google.com/drive/11Zi77gs1FKoEqfPqYa2HtTENiWZyQAO2?usp=sharing" target="_blank" rel="noopener noreferrer nofollow">notebook do Colaboratory que acompanha este vídeo.</a> Adicione o código do vídeo ao notebook do Colaboratory de álgebra para ver como resolver para X usando o Python. Em seguida, mude o código se você quiser, teste-o e compare-o à resolução com lápis e papel. Lembre-se de que a entrada da equação precisa estar na sintaxe do Python.
# --question--
## --assignment--
Add the code to solve for x from the video to your algebra Colab notebook.
Adicione o código para resolver para x do vídeo ao seu notebook do Colaboratory de álgebra.
## --text--
In Python, what is the library you import to solve algebra problems with variables?
Em Python, qual é a biblioteca que você importa para resolver problemas de álgebra com variáveis?
## --answers--
@@ -1,6 +1,6 @@
---
id: 6331d28ab51aeedd1a2bd650
title: "Linear Equations"
title: "Equações lineares"
challengeType: 15
videoId: u0bgovPh4ME
dashedName: linear-equations
@@ -8,19 +8,19 @@ dashedName: linear-equations
# --description--
This video will show you the math behind finding the y-intercept in a linear function, so you can develop the whole equation. Then the video will show you how to graph the whole function. You will also see how to do the whole process with Python code.
Este vídeo mostrará a matemática por trás do cálculo da interceptação do eixo y em uma função linear, assim você poderá desenvolver a equação inteira. Então, o vídeo mostrará como criar o gráfico de uma função inteira. Você também verá como fazer todo o processo com o código em Python.
Here is the <a href="https://colab.research.google.com/drive/1UJ1w-XFTuCfK6FI3H2GT0lbxd2HO3tQ6?usp=sharing" target="_blank" rel="noopener noreferrer nofollow">Colab notebook to go with the last two videos,</a> so you can see the formulas.
Aqui está o <a href="https://colab.research.google.com/drive/1UJ1w-XFTuCfK6FI3H2GT0lbxd2HO3tQ6?usp=sharing" target="_blank" rel="noopener noreferrer nofollow">notebook do Colaboratory que acompanha os dois últimos vídeos</a> para que você possa ver as fórmulas.
# --question--
## --assignment--
Add code to your algebra Colab notebook to graph a function from points or from equation input.
Adicione código ao seu notebook do Colaboratory de álgebra para representar graficamente uma função a partir de pontos ou de entradas na equação.
## --text--
If you know the slope ("m") and you have one (x,y) coordinate point, which of the following equations could you use to find "b", representing the y-intercept in Python?
Se você souber o coeficiente angular ("m") e se tiver um ponto de coordenadas (x, y), qual das seguintes equações você poderia usar para encontrar "b", representando o ponto de interceptação do eixo y em Python?
## --answers--
@@ -1,6 +1,6 @@
---
id: 6363d25c9078df117ce4c403
title: "Parent Graphs and Polynomials: Extra"
title: "Gráficos pai e polinômios: extra"
challengeType: 15
videoId: YDlXmmRgQJI
dashedName: parent-graphs-and-polynomials-extra
@@ -8,15 +8,15 @@ dashedName: parent-graphs-and-polynomials-extra
# --description--
This next video will show you how to add sliders to your graphs, to see them change in real time. You will also see ways to use loops to find the roots of a graph, and how this method is different from factoring.
Este próximo vídeo mostrará como adicionar botões deslizantes em seus gráficos, para ver as alterações em tempo real. Você também verá maneiras de usar laços para encontrar as raízes de um gráfico e como este método é diferente da fatoração.
Here is the <a href="https://colab.research.google.com/drive/1bspkmQVcKOXUuk-Orb0Mwl0GUGbqMpka?usp=sharing" target="_blank" rel="noopener noreferrer nofollow">Colab notebook to go along with this video.</a>
Aqui está o <a href="https://colab.research.google.com/drive/1bspkmQVcKOXUuk-Orb0Mwl0GUGbqMpka?usp=sharing" target="_blank" rel="noopener noreferrer nofollow">notebook do Colaboratory que acompanha este vídeo.</a>
# --question--
## --text--
How many sliders would you add to change the coefficients in a quadratic graph?
Quantos botões deslizantes você adicionaria para alterar os coeficientes em um gráfico de segundo grau?
## --answers--
@@ -1,6 +1,6 @@
---
id: 6331caa1b51aeedd1a2bd644
title: "Introduction to College Algebra with Python"
title: "Introdução à álgebra universitária com Python"
challengeType: 15
videoId: bO3Sn10-XNw
dashedName: introduction-to-college-algebra-with-python
@@ -8,23 +8,23 @@ dashedName: introduction-to-college-algebra-with-python
# --description--
This first video includes an introduction to the course, how it will work, and how to use Google Colaboratory. Follow along to create your first Colab notebook.
Este primeiro vídeo inclui uma introdução ao curso, como ele vai funcionar e como usar o Google Colaboratory. Acompanhe-o para criar o seu primeiro notebook do Colaboratory.
**Videos throughout these courses will reference problems from these two textbooks:**
**Os vídeos deste curso farão referência a problemas destes dois livros:**
\- <a href="https://lyryx.com/subjects/business/business-mathematics/" target="_blank" rel="noopener noreferrer nofollow">Business Math, a Step-by-Step Handbook (2021) by Jean-Paul Oliver</a>
\- <a href="https://lyryx.com/subjects/business/business-mathematics/" target="_blank" rel="noopener noreferrer nofollow">Business Math, a Step-by-Step Handbook (2021), de Jean-Paul Oliver</a>
\- <a href="https://openstax.org/details/books/algebra-and-trigonometry" target="_blank" rel="noopener noreferrer nofollow">Algebra and Trigonometry by Jay Abramson</a>
\- <a href="https://openstax.org/details/books/algebra-and-trigonometry" target="_blank" rel="noopener noreferrer nofollow">Algebra and Trigonometry, de Jay Abramson</a>
# --question--
## --assignment--
Create an algebra <a href="https://drive.google.com/" target="_blank" rel="noopener noreferrer nofollow">Colab notebook on your google drive</a> so you can follow along with the videos.
Crie um <a href="https://drive.google.com/" target="_blank" rel="noopener noreferrer nofollow">notebook do Colaboratory de álgebra no seu Google Drive</a> para que você possa acompanhar os vídeos.
## --text--
When adding text in Google Colab, what symbol would you use to create a heading that will appear in the table of contents?
Ao adicionar texto no Google Colaboratory, qual símbolo você usaria para criar um título que aparecerá no sumário?
## --answers--
@@ -1,6 +1,6 @@
---
id: 6331d29fb51aeedd1a2bd653
title: "Solving Proportions"
title: "Resolução de proporções"
challengeType: 15
videoId: 61A3PNx1hjY
dashedName: solving-proportions
@@ -8,31 +8,31 @@ dashedName: solving-proportions
# --description--
Now we get to the math content. This video will show you how to set up and solve proportions and write code to solve for variables.
Passemos, agora, ao conteúdo da matemática. Este vídeo mostrará como configurar e resolver proporções e como escrever código para resolver para variáveis.
Here is the <a href="https://colab.research.google.com/drive/1Q7nCcbrnoYttkwiHB_nQ-X1JuLpUmtRD?usp=sharing" target="_blank" rel="noopener noreferrer nofollow">Colab notebook to go along with this video.</a> If you have not done so yet, set up your algebra Colab notebook from the last video. Then, add the code from this video to it.
Aqui está o <a href="https://colab.research.google.com/drive/1Q7nCcbrnoYttkwiHB_nQ-X1JuLpUmtRD?usp=sharing" target="_blank" rel="noopener noreferrer nofollow">notebook do Colaboratory que acompanha este vídeo.</a> Se você ainda não fez isso, configure seu notebook do Colaboratory de álgebra do vídeo passado. Em seguida, adicione o código deste vídeo a ele.
# --question--
## --assignment--
Add the code from the video to the algebra Colab notebook you created in the first step.
Adicione o código do vídeo ao notebook do Colaboratory de álgebra que você criou no primeiro passo.
## --text--
In solving a proportion, if one numerator is zero, does the other numerator have to be zero for the statement to be true?
Ao resolver uma proporção, se um numerador for zero, o outro numerador precisa ser zero para que a instrução seja verdadeira?
## --answers--
Yes
Sim
---
No
Não
---
Sometimes
Às vezes
## --video-solution--
@@ -1,6 +1,6 @@
---
id: 63dbd1335d93712ff177d96a
title: "Simple and Compound Interest: Extra"
title: "Juros simples e compostos: extra"
challengeType: 15
videoId: 2cbrstoKNSc
dashedName: simple-and-compound-interest-extra
@@ -8,13 +8,13 @@ dashedName: simple-and-compound-interest-extra
# --description--
Here is a detour from the Python code, as this video shows you how to create mortgage payment amortization tables in Google Sheets. You will also learn about how to use a very similar setup to estimate retirement account investment returns. This is the video that shows you where your money is going.
Aqui, desviamos um pouco do código em Python, pois este vídeo mostra como criar tabelas de amortização de hipoteca nas planilhas do Google. Você também aprenderá sobre como usar uma configuração muito semelhante para estimar os rendimentos do investimento na conta para sua aposentadoria. Este é o vídeo que mostra para onde o seu dinheiro está indo.
# --question--
## --text--
What marker do you use to attach a formula to a cell in a spreadsheet?
Qual marcador você usa para anexar uma fórmula a uma célula em uma planilha?
## --answers--
@@ -11,7 +11,7 @@ dashedName: escape-sequences-in-strings
Лапки – не єдині символи, що можуть бути <dfn>екрановані</dfn> в рядку. Екрановані символи дозволяють використовувати символи, які інакше неможливо використати.
<table class='table table-striped'><thead><tr><th>Код</th><th>Вивід</th></tr></thead><tbody><tr><td><code>\'</code></td><td>одинарні лапки</td></tr><tr><td><code>\"</code></td><td>подвійні лапки</td></tr><tr><td><code>\\</code></td><td>зворотна коса риска</td></tr><tr><td><code>\n</code></td><td>новий рядок</td></tr><tr><td><code>\t</code></td><td>табуляція</td></tr><tr><td><code>\r</code></td><td>повернення каретки</td></tr><tr><td><code>\b</code></td><td>границі слова</td></tr><tr><td><code>\f</code></td><td>перевід сторінки</td></tr></tbody></table>
<table class='table table-striped'><thead><tr><th>Код</th><th>Вивід</th></tr></thead><tbody><tr><td><code>\'</code></td><td>одинарні лапки</td></tr><tr><td><code>\"</code></td><td>подвійні лапки</td></tr><tr><td><code>\\</code></td><td>зворотна коса риска</td></tr><tr><td><code>\n</code></td><td>новий рядок</td></tr><tr><td><code>\t</code></td><td>табуляція</td></tr><tr><td><code>\r</code></td><td>повернення каретки</td></tr><tr><td><code>\b</code></td><td>backspace</td></tr><tr><td><code>\f</code></td><td>перевід сторінки</td></tr></tbody></table>
*Зверніть увагу, що сама зворотня коса риска повинна бути екранована для того, щоб вона відображалась.*
@@ -9,7 +9,7 @@ dashedName: selecting-from-many-options-with-switch-statements
# --description--
Якщо ви маєте багато варіантів для вибору, використовуйте інструкцію <dfn>switch</dfn>. Інструкція `switch` тестує значення та може мати багато інструкцій <dfn>case</dfn>, які визначають можливі значення. Інструкції виконуються від першого відповідного значення `case` до тих пір, поки не зіткнуться із `break`.
If you need to match one value against many options, you can use a <dfn>switch</dfn> statement. A `switch` statement compares the value to the <dfn>case</dfn> statements which define various possible values. Any valid JavaScript statements can be executed inside a <dfn>case</dfn> block and will run from the first matched `case` value until a `break` is encountered.
Ось приклад інструкції `switch`:
@@ -9,7 +9,7 @@ dashedName: step-1
Статистика — це спосіб використання математики, щоб зрозуміти дані. Завдяки їй легко зрозуміти закономірності та тенденції інформації, щоб зробити прогнози та прийняти рішення на її основі.
У цьому завданні ви створите статистичний калькулятор, який приймає набір чисел та повертає середнє число, медіану, хвильове число, середнє квадратичне відхилення та дисперсію.
У цьому завданні ви створите статистичний калькулятор, який приймає набір чисел та повертає середнє значення, медіану, моду, стандартне відхилення та дисперсію.
Вам вже надано HTML та CSS. Розгляньте код: ви можете помітити, що функція `calculate` викликається тоді, коли надіслана форма. Коли будете готові, оголосіть змінну `calculate` та призначте їй порожню функцію у файлі `script.js`.
@@ -7,7 +7,7 @@ dashedName: step-9
# --description--
Це все, що ви можете зробити з обчислюваною функцією. Час написати логіку середнього числа.
Це все, що ви можете зробити з обчислюваною функцією. Час написати логіку для середнього значення.
Створіть порожню функцію під назвою `getMean`. Вона повинна приймати єдиний параметр `array`.
@@ -7,7 +7,7 @@ dashedName: step-10
# --description--
<dfn>Середнє число</dfn> — це середнє значення всіх чисел у списку. Спочатку, щоб розрахувати середнє число, потрібно знайти суму всіх чисел у списку. Масиви мають інший метод під назвою `.reduce()`, який ідеальний для такого випадку. Метод `.reduce()` приймає масив та застосовує функцію зворотного виклику, щоб стиснути масив у єдине значення.
<dfn>Середнє значення</dfn> — це середнє арифметичне значення всіх чисел у списку. Спочатку, щоб обчислити середнє значення, потрібно знайти суму всіх чисел у списку. Масиви мають інший метод під назвою `.reduce()`, який ідеальний для такого випадку. Метод `.reduce()` приймає масив та застосовує функцію зворотного виклику, щоб стиснути масив у єдине значення.
Оголосіть змінну `sum` та призначте їй `array.reduce()`.
@@ -25,7 +25,7 @@ assert.match(getMean.toString(), /sum/);
assert.match(getMean.toString(), /array\.reduce\(\)/);
```
Ви повинні присвоїти результат `array.reduce()` до змінної `sum`.
Ви повинні призначити результат `array.reduce()` до змінної `sum`.
```js
assert.match(getMean.toString(), /sum\s*=\s*array\.reduce\(\)/);
@@ -7,7 +7,7 @@ dashedName: step-13
# --description--
Наступне, що потрібно зробити для знаходження середнього числа — поділити суму чисел на кількість чисел у списку.
Наступне, що потрібно зробити для знаходження середнього значення — поділити суму чисел на кількість чисел у списку.
Оголосіть змінну `mean` та призначте їй значення `sum`, поділене на довжину `array`.
@@ -7,7 +7,7 @@ dashedName: step-18
# --description--
Якщо ви перевірите свою форму зі списком чисел, ви маєте побачити середнє число на сторінці. Однак це працює лише через те, що iframe freeCodeCamp має спеціальні налаштування. Зазвичай, коли форма надіслана, подія призводить до оновлення сторінки.
Якщо ви перевірите свою форму зі списком чисел, ви маєте побачити середнє значення на сторінці. Однак це працює лише через те, що iframe freeCodeCamp має спеціальні налаштування. Зазвичай, коли форма надіслана, подія призводить до оновлення сторінки.
Щоб виправити це, додайте `return false;` в атрибут `onsubmit` після виклику `calculate();`.
@@ -7,15 +7,15 @@ dashedName: step-22
# --description--
The next step is to find the number in the middle of the list. If the list has an odd number of numbers, the middle number is the median. If the list has an even number of numbers, the median is the average of the two middle numbers.
Наступний крок — знайти число посередині списку. Якщо список містить непарну кількість чисел, то число посередині є медіаною. Якщо список містить парну кількість чисел, то медіаною є середнє значення двох чисел посередині.
You can check if a number is even or odd with the <dfn>modulus operator</dfn>, which is represented by the `%` symbol. This operator returns the remainder of the division of two numbers. If the remainder is `0`, the number is even. If the remainder is `1`, the number is odd:
Ви можете перевірити кількість на парність/непарність за допомогою <dfn>оператора modulus</dfn>, який зображено символом `%`. Цей оператор повертає залишок від ділення двох чисел. Якщо залишком є `0`, то кількість парна. Якщо залишком є `1`, то кількість непарна:
```js
array.length % 2 === 0;
```
Declare a `median` variable. Using the ternary operator, check if the length of `array` is even. If the length of `array` is even, find the two middle numbers and calculate the mean of those numbers. If the length of `array` is odd, find the middle number and assign it to the `median` variable.
Оголосіть змінну `median`. Використовуючи тернарний оператор, перевірте, чи довжина `array` є парною. Якщо довжина `array` є парною, то знайдіть два числа посередині та обчисліть їхнє середнє значення. Якщо довжина `array` є непарною, то знайдіть число посередині та призначте його до змінної `median`.
# --hints--
@@ -25,19 +25,19 @@ Declare a `median` variable. Using the ternary operator, check if the length of
assert.match(getMedian.toString(), /median\s*=/);
```
Your `median` variable should use a ternary operator to check if the `array.length` is even.
Змінна `median` повинна використовувати тернарний оператор, щоб перевірити, чи довжина `array.length` є парною.
```js
assert.match(getMedian.toString(), /median\s*=\s*array\.length\s*%\s*2\s*===\s*0\s*\?/);
```
If the `array.length` is even, your `median` variable should use the `getMean` function to calculate the mean of the two middle numbers. Your first argument should be the value of `sorted` at `array.length / 2`, and the second at `array.length / 2 - 1`.
Якщо довжина `array.length` є парною, змінна `median` має використовувати функцію `getMean`, щоб обчислити середнє значення двох чисел посередині. Першим аргументом має бути значення `sorted` в `array.length / 2`, а другим — в `array.length / 2 - 1`.
```js
assert.match(getMedian.toString(), /median\s*=\s*array\.length\s*%\s*2\s*===\s*0\s*\?\s*getMean\(\s*\[sorted\[array\.length\s*\/\s*2\]\s*,\s*sorted\[\s*array\.length\s*\/\s*2\s*-\s*1\]\]\)\s*\:/);
```
If the `array.length` is odd, your `median` variable should assign the middle number to the `median` variable. The middle number is the value of `sorted` at `Math.floor(array.length / 2)`.
Якщо довжина `array.length` є непарною, змінна `median` має призначити середнє число до змінної `median`. Середнє число є значенням `sorted` в `Math.floor(array.length / 2)`.
```js
assert.match(getMedian.toString(), /median\s*=\s*array\.length\s*%\s*2\s*===\s*0\s*\?\s*getMean\(\s*\[sorted\[array\.length\s*\/\s*2\]\s*,\s*sorted\[\s*array\.length\s*\/\s*2\s*-\s*1\]\]\)\s*\:\s*sorted\[\s*Math\.floor\(\s*array\.length\s*\/\s*2\)\];/);
@@ -7,9 +7,9 @@ dashedName: step-23
# --description--
Finally, return the value of `median`.
Тепер потрібно повернути значення `median`.
Like the `getMean` function, you could condense this code into one line and reduce the number of variables you instantiate. However, it is important to remember that shorter code is not always better code. In this case, reducing the lines of code would make the code harder to read and understand, impacting future maintainability.
Як і з функцією `getMean`, ви б могли зменшити цей код до одного рядка та зменшити кількість створених змінних. Однак важливо пам’ятати: короткий код не завжди є кращим. У цьому разі зменшення кількості рядків коду призведе до того, що його важче читати та розуміти, впливаючи на майбутнє обслуговування.
# --hints--
@@ -7,9 +7,9 @@ dashedName: step-24
# --description--
Like you did with your `getMean` function, you need to add your `getMedian` function to your `calculate` logic.
Як і з функцією `getMean`, вам потрібно додати функцію `getMedian` до логіки `calculate`.
Declare a variable `median` and assign it the value of `getMedian(numbers)`. Then, query the DOM for the `#median` element and set the `textContent` to `median`.
Оголосіть змінну `median` та призначте їй значення `getMedian(numbers)`. Потім запитайте DOM про елемент `#median` та встановіть `textContent` на `median`.
# --hints--
@@ -19,13 +19,13 @@ Declare a variable `median` and assign it the value of `getMedian(numbers)`. The
assert.match(calculate.toString(), /median\s*=/);
```
Your `median` variable should be assigned the value of `getMedian(numbers)`.
Змінній `median` потрібно призначити значення `getMedian(numbers)`.
```js
assert.match(calculate.toString(), /median\s*=\s*getMedian\(numbers\)/);
```
Your `calculate` function should query the DOM for the `#median` element and set the `textContent` to `median`.
Функція `calculate` повинна запитати DOM про елемент `#median` та встановити `textContent` на `median`.
```js
assert.match(calculate.toString(), /document\.querySelector\(('|")#median\1\)\.textContent\s*=\s*median/);
@@ -7,7 +7,7 @@ dashedName: step-25
# --description--
Your next calculation is the <dfn>mode</dfn>, which is the number that appears most often in the list. To get started, declare a `getMode` function that takes the same `array` parameter you have been using.
Наступним обчисленням буде <dfn>мода</dfn>, тобто число, яке найчастіше зустрічається у списку. Для початку оголосіть функцію `getMode`, яка приймає той самий параметр `array`, який ви використовували.
# --hints--
@@ -7,7 +7,7 @@ dashedName: step-26
# --description--
In your new function, declare an empty `counts` object. You will use this to track the number of times each number appears in the list.
У новій функції оголосіть порожній об’єкт `counts`. Ви використовуватимете його, щоб відстежувати, скільки разів число з’явилось у списку.
# --hints--
@@ -7,13 +7,13 @@ dashedName: step-27
# --description--
Remember that the `.forEach()` method allows you to run a callback function for each element in the array.
Пам’ятайте, що метод `.forEach()` дозволяє застосувати функцію зворотного виклику до кожного елементу в масиві.
Use the `.forEach()` method to loop through the `array`. In the callback, use the `el` argument to access the `counts` object and increment the count for each number.
Використайте метод `.forEach()`, щоб циклічно переглянути `array`. Використайте аргумент `el` у функції зворотного виклику, щоб отримати доступ до об’єкта `counts` та збільшити лічильник для кожного числа.
# --hints--
Your `getMode` function should use the `.forEach()` method.
Ваша функція `getMode` повинна використовувати метод `.forEach()`.
```js
assert.match(getMode.toString(), /array\.forEach\(/);
@@ -26,7 +26,7 @@ console.log(getMode.toString());
assert.match(getMode.toString(), /(array\.forEach\(\(?\s*el\s*\)?\s*=>|array\.forEach\(function\s*\(?el\)?\s*\{)/);
```
Your `.forEach()` method should increment the count for each number. Don't forget the fallback value.
Метод `.forEach()` повинен збільшувати лічильник для кожного числа. Не забудьте про запасне значення.
```js
assert.match(getMode.toString(), /(array\.forEach\(\(?\s*el\s*\)?\s*=>|array\.forEach\(function\s*\(?el\)?\s*\{)\s*\{?\s*(return)?\s*counts\[\s*el\s*\]\s*=\s*\(\s*counts\[\s*el\s*\]\s*\|\|\s*0\s*\)\s*\+\s*1\s*\}?/);
@@ -7,11 +7,11 @@ dashedName: step-28
# --description--
There are a few edge cases to account for when calculating the mode of a dataset. First, if every value appears the same number of times, there is no mode.
При обчисленні моди потрібно звернути увагу на декілька випадків. Перше: якщо всі значення з’являються однакову кількість разів, моди не існує.
To calculate this, you will use a `Set`. A `Set` is a data structure that only allows unique values. If you pass an array into the `Set` constructor, it will remove any duplicate values.
Щоб обчислити це, використовуйте `Set`. `Set` — це структура даних, яка дозволяє лише унікальні значення. Якщо передати масив до конструктора `Set`, він вилучить всі повторювані значення.
Start by creating an `if` statement. In the condition, create a `Set` with `new Set()` and pass it the `Object.values()` of your `counts` object. If the `size` property of this `Set` is equal to `1`, that tells you every value appears the same number of times. In this case, return `null` from your function.
Розпочніть зі створення інструкції `if`. В умові створіть `Set` із `new Set()` та передайте йому `Object.values()` об’єкта `counts`. Якщо властивість `size` цього `Set` дорівнює `1`, то значення з’являються однакову кількість разів. У такому разі поверніть `null` зі своєї функції.
# --hints--
@@ -21,19 +21,19 @@ Start by creating an `if` statement. In the condition, create a `Set` with `new
assert.match(getMode.toString(), /if\s*\(/);
```
Your `if` statement should create a new `Set` and pass the `Object.values()` of your `counts` object.
Інструкція `if` повинна створити новий `Set` та передати `Object.values()` об’єкта `counts`.
```js
assert.match(getMode.toString(), /if\s*\(\s*new\s+Set\s*\(\s*Object\.values\s*\(\s*counts\s*\)/);
```
Your `if` statement should check if the `size` property of the new `Set` is equal to `1`.
Інструкція `if` повинна перевіряти, чи властивість `size` нового `Set` дорівнює `1`.
```js
assert.match(getMode.toString(), /if\s*\(\s*new\s+Set\s*\(\s*Object\.values\s*\(\s*counts\s*\)\s*\)\s*\.size\s*===\s*1/);
```
Your `if` statement should return `null` if the `size` property of the new `Set` is equal to `1`.
Інструкція `if` повинна повернути `null`, якщо властивість `size` нового `Set` дорівнює `1`.
```js
assert.match(getMode.toString(), /if\s*\(\s*new\s+Set\s*\(\s*Object\.values\s*\(\s*counts\s*\)\s*\)\.size\s*===\s*1\s*\)\s*\{?\s*return\s+null;\s*\}?/);
@@ -7,9 +7,9 @@ dashedName: step-29
# --description--
Now you need to find the value that occurs with the highest frequency. You'll use the `Object.keys()` method for this.
Тепер вам потрібно знайти значення, яке з’являється найчастіше. Для цього ви використовуватимете метод `Object.keys()`.
Start by declaring a `highest` variable, and assigning it the value of the `counts` object's `Object.keys()` method.
Для початку оголосіть змінну `highest` та призначте їй значення методу `Object.keys()` об’єкта `counts`.
# --hints--
@@ -25,7 +25,7 @@ assert.match(getMode.toString(), /highest\s*=/);
assert.match(getMode.toString(), /Object\.keys\(\s*counts\s*\)/);
```
Функція `getMode` повинна використовувати метод `Object.keys()`, щоб отримати ключі об’єкта `counts` та присвоїти їх до змінної `highest`.
Функція `getMode` повинна використовувати метод `Object.keys()`, щоб отримати ключі об’єкта `counts` та призначити їх до змінної `highest`.
```js
assert.match(getMode.toString(), /highest\s*=\s*Object\.keys\(\s*counts\s*\)/);
@@ -7,33 +7,33 @@ dashedName: step-30
# --description--
Now you need to sort the values properly. Chain the `.sort()` method to your `Object.keys()` call.
Тепер вам потрібно відсортувати значення належним чином. З’єднайте метод `.sort()` із викликом `Object.keys()`.
For the callback, you'll need to use the `counts` object to compare the values of each key. You can use the `a` and `b` parameters to access the keys. Then, return the value of `counts[b]` minus the value of `counts[a]`.
Щодо функції зворотного виклику: вам потрібно використати об’єкт `counts`, щоб порівняти значення кожного ключа. Ви можете використати параметри `a` та `b`, щоб отримати доступ до ключів. Потім поверніть значення `counts[b]` мінус значення `counts[a]`.
Finally, access the first element in the array using bracket notation to complete your `highest` variable.
Вкінці отримайте доступ до першого елемента масиву, використавши дужкову нотацію, щоб закінчити змінну `highest`.
# --hints--
Your `getMode` function should use the `sort` method to sort the `Object.keys()` array.
Функція `getMode` повинна використовувати метод `sort`, щоб відсортувати масив `Object.keys()`.
```js
assert.match(getMode.toString(), /highest\s*=\s*Object\.keys\(\s*counts\s*\)\.sort\(/)
```
Your `getMode` function should pass a callback to the `sort` method with parameters `a` and `b`.
Функція `getMode` повинна передати функцію зворотного виклику до методу `sort` з параметрами `a` та `b`.
```js
assert.match(getMode.toString(), /highest\s*=\s*Object\.keys\(\s*counts\s*\)\.sort\(function\s*\(\s*a\s*,\s*b\s*\)/)
```
Your `getMode` function should use the `sort` method to sort the `Object.keys()` array and return the value of `counts[b]` minus the value of `counts[a]`.
Функція `getMode` повинна використовувати метод `sort`, щоб відсортувати масив `Object.keys()` та повернути значення `counts[b]` мінус значення `counts[a]`.
```js
assert.match(getMode.toString(), /highest\s*=\s*Object\.keys\(\s*counts\s*\)\.sort\(\s*function\s*\(\s*a\s*,\s*b\s*\)\s*\{\s*return\s*counts\[\s*b\s*\]\s*-\s*counts\[\s*a\s*\];?\s*\}\s*\)/)
```
Your `highest` variable should have the value of the first entry in the sorted `Object.keys(counts)` array.
Змінна `highest` повинна мати значення першого запису відсортованого масиву `Object.keys(counts)`.
```js
assert.match(getMode.toString(), /highest\s*=\s*Object\.keys\(\s*counts\s*\)\.sort\(\s*function\s*\(\s*a\s*,\s*b\s*\)\s*\{\s*return\s*counts\[\s*b\s*\]\s*-\s*counts\[\s*a\s*\];?\s*\}\s*\)\[0\];/)
@@ -7,9 +7,9 @@ dashedName: step-31
# --description--
If multiple numbers in a series occur at the same highest frequency, they are all considered the mode. Otherwise, the mode is the number that occurs most often, that single number is the mode.
Якщо декілька чисел з’являються однакову кількість разів, вони всі вважаються модою. В іншому разі модою вважається те число, яке з’являється найчастіше.
Thankfully, you can handle both of these cases at once with the `.filter()` method. Start by declaring a `mode` variable and assigning it the value of `Object.keys(counts)`.
На щастя, ви можете впоратись з двома випадками одночасно завдяки методу `.filter()`. Для початку оголосіть змінну `mode` та призначте їй значення `Object.keys(counts)`.
# --hints--
@@ -19,7 +19,7 @@ Thankfully, you can handle both of these cases at once with the `.filter()` meth
assert.match(getMode.toString(), /mode\s*=/);
```
Функція `getMode` повинна використовувати метод `Object.keys()`, щоб отримати ключі об’єкта `counts` та присвоїти їх до змінної `mode`.
Функція `getMode` повинна використовувати метод `Object.keys()`, щоб отримати ключі об’єкта `counts` та призначити їх до змінної `mode`.
```js
assert.match(getMode.toString(), /mode\s*=\s*Object\.keys\(\s*counts\s*\)/);
@@ -7,23 +7,23 @@ dashedName: step-32
# --description--
Now chain the filter method to your latest `Object.keys()` call. The callback function should return whether the value of `counts[el]` is equal to your `counts[highest]`.
Тепер з’єднайте метод filter з останнім викликом `Object.keys()`. Функція зворотного виклику повинна повернути, чи значення `counts[el]` дорівнює `counts[highest]`.
# --hints--
You should chain `.filter()` to your last `Object.keys()` call.
Ви повинні з’єднати `.filter()` з останнім викликом `Object.keys()`.
```js
assert.match(getMode.toString(), /mode\s*=\s*Object\.keys\(\s*counts\s*\)\.filter\(/);
```
Your `.filter()` method should take a callback function with a parameter `el`.
Метод `.filter()` повинен приймати функцію зворотного виклику з параметром `el`.
```js
assert.match(getMode.toString(), /mode\s*=\s*Object\.keys\(\s*counts\s*\)\.filter\(function\s*\(\s*el\s*\)/);
```
Your `.filter()` method should return whether the value of `counts[el]` is equal to `counts[highest]`.
Метод `.filter()` повинен повернути, чи значення `counts[el]` дорівнює `counts[highest]`.
```js
assert.match(getMode.toString(), /mode\s*=\s*Object\.keys\(\s*counts\s*\)\.filter\(function\s*\(\s*el\s*\)\s*\{\s*return\s*counts\[\s*el\s*\]\s*===\s*counts\[\s*highest\s*\];\s*\}/);
@@ -7,9 +7,9 @@ dashedName: step-33
# --description--
Time to return your `mode` variable.
Час повернути змінну `mode`.
`mode` is an array, so return it as a string with the `.join()` method. Separate the elements with a comma followed by a space.
`mode` є масивом, тому поверніть її як рядок за допомогою методу `.join()`. Розділіть елементи комою та пробілом.
# --hints--
@@ -19,13 +19,13 @@ Time to return your `mode` variable.
assert.match(getMode.toString(), /return\s*mode\s*/)
```
Your `mode` variable should be returned as a string with the `join` method.
Змінна `mode` повинна повернутись як рядок завдяки методу `join`.
```js
assert.match(getMode.toString(), /return\s*mode\.join\(/)
```
You should separate the elements of the `mode` array with a comma and a space.
Ви повинні розділити елементи масиву `mode` комою та пробілом.
```js
assert.match(getMode.toString(), /return\s*mode\.join\(\s*('|"),\s\1\s*\);/)
@@ -7,7 +7,7 @@ dashedName: step-34
# --description--
Add your `getMode()` function to your `calculate` logic, and update the respective HTML element.
Додайте функцію `getMode()` до логіки `calculate` та оновіть відповідний елемент HTML.
# --hints--
@@ -17,7 +17,7 @@ Add your `getMode()` function to your `calculate` logic, and update the respecti
assert.match(calculate.toString(), /mode\s*=\s*getMode\(\s*numbers\s*\);/);
```
Your `calculate` function should query the DOM for the `#mode` element and set the `textContent` to `mode`.
Функція `calculate` повинна запитати DOM про елемент `#mode` та встановити `textContent` на `mode`.
```js
assert.match(calculate.toString(), /document\.querySelector\(('|")#mode\1\)\.textContent\s*=\s*mode;/);
@@ -7,15 +7,15 @@ dashedName: step-35
# --description--
Your next calculation is the <dfn>range</dfn>, which is the difference between the largest and smallest numbers in the list.
Наступним обчисленням буде <dfn>розмах</dfn>, тобто різниця між найбільшим та найменшим числом у списку.
You previously learned about the global `Math` object. `Math` has a `.min()` method to get the smallest number from a series of numbers, and the `.max()` method to get the largest number. Here's an example that gets the smallest number from an array:
Раніше ви дізнались про глобальний об’єкт `Math`. `Math` має метод `.min()` для отримання найменшого числа та метод `.max()` для отримання найбільшого числа. Ось приклад того, як отримати найменше число масиву:
```js
Math.min(1, 9, 11, -3, 0.5);
```
Declare a `getRange` function that takes the same `array` parameter you have been using. Using `Math.min()`, `Math.max()`, and the spread operator, return the difference between the largest and smallest numbers in the list.
Оголосіть функцію `getRange`, яка приймає той самий параметр `array`, який ви використовували. Використовуючи `Math.min()`, `Math.max()` та spread-оператор, поверніть різницю між найбільшим та найменшим числом у списку.
# --hints--
@@ -31,25 +31,25 @@ assert.isFunction(getRange);
assert.match(getRange.toString(), /array/);
```
Your `getRange` function should use the spread operator on the `array` parameter.
Функція `getRange` повинна використовувати spread-оператор на параметрі `array`.
```js
assert.match(code.split("getRange")[1], /\.\.\.array/);
```
Your `getRange` function should use `Math.max` on the spread `array` parameter.
Функція `getRange` повинна використовувати `Math.max` на spread-параметрі `array`.
```js
assert.match(code.split("getRange")[1], /Math\.max\(\s*\.\.\.array\s*\)/);
```
Your `getRange` function should use `Math.min` on the spread `array` parameter.
Функція `getRange` повинна використовувати `Math.min` на spread-параметрі `array`.
```js
assert.match(code.split("getRange")[1], /Math\.min\(\s*\.\.\.array\s*\)/);
```
Your `getRange` function should return the difference between the largest and smallest numbers in the list.
Функція `getRange` повинна повернути різницю між найбільшим та найменшим числом у списку.
```js
assert.equal(getRange([1, 2, 3, 4, 5]), 4);
@@ -7,17 +7,17 @@ dashedName: step-36
# --description--
Add the logic for calculating and displaying the range to your `calculate` function.
Додайте логіку для обчислення та показу розмаху до функції `calculate`.
# --hints--
Your `calculate` function should set a `range` variable to the result of `getRange(numbers)`.
Функція `calculate` повинна налаштовувати змінну `range` на результат `getRange(numbers)`.
```js
assert.match(calculate.toString(), /range\s*=\s*getRange\(numbers\);/);
```
Your `calculate` function should set the `#range` element's `textContent` to the `range` variable.
Функція `calculate` повинна налаштовувати `textContent` елемента `#range` на змінну `range`.
```js
assert.match(calculate.toString(), /document\.querySelector\(('|")#range\1\)\.textContent\s*=\s*range;/);
@@ -7,9 +7,9 @@ dashedName: step-37
# --description--
The <dfn>variance</dfn> of a series represents how much the data deviates from the mean, and can be used to determine how spread out the data are. The variance is calculated in a few steps.
<dfn>Дисперсія</dfn> показує, наскільки дані відхиляються від середнього значення. Її використовують, щоб визначити, наскільки поширені дані. Дисперсія обчислюється за декілька кроків.
Start by declaring a `getVariance` function that takes an `array` parameter. Within that function, declare a `mean` variable and assign it the value of the `getMean` function, passing `array` as the argument.
Для початку оголосіть функцію `getVariance`, яка приймає параметр `array`. В межах цієї функції оголосіть змінну `mean` та призначте їй значення функції `getMean`, передавши `array` як аргумент.
# --hints--
@@ -31,7 +31,7 @@ assert.match(getVariance.toString(), /array/);
assert.match(getVariance.toString(), /mean\s*=/);
```
Your `mean` variable should be assigned the value of the `getMean` function, passing the `array` argument.
Змінній `mean` потрібно призначити значення функції `getMean`, передавши аргумент `array`.
```js
assert.match(getVariance.toString(), /mean\s*=\s*getMean\(\s*array\s*\);/);
@@ -7,7 +7,7 @@ dashedName: step-38
# --description--
The next step is to calculate how far each element is from the mean. Declare a `differences` variable, and assign it the value of `array.map()`. For the callback, return the value of `el` minus `mean`.
У наступному кроці потрібно обчислити, наскільки далеко кожен елемент від середнього значення. Оголосіть змінну `differences` та призначте їй значення `array.map()`. Щодо функції зворотного виклику: поверніть значення `el` мінус `mean`.
# --hints--
@@ -29,7 +29,7 @@ assert.match(getVariance.toString(), /differences\s*=\s*array\.map\(/);
assert.match(getVariance.toString(), /differences\s*=\s*array\.map\(function\s*\(?\s*el\s*\)?/);
```
Your `map` callback should return the value of `el` minus `mean`.
Функція зворотного виклику `map` повинна повернути значення `el` мінус `mean`.
```js
assert.match(getVariance.toString(), /differences\s*=\s*array\.map\(function\s*\(?\s*el\s*\)?\s*\{\s*return\s*el\s*-\s*mean;?\s*\}/);
@@ -7,9 +7,9 @@ dashedName: step-39
# --description--
The next step is to square each of the differences. To square a value, you can use the `**` operator. For example, `3 ** 2` would return `9`.
У наступному кроці потрібно піднести кожну різницю до квадрата. Щоб піднести значення до квадрата, можна використати оператор `**`. Наприклад, `3 ** 2` поверне `9`.
Declare a `squaredDifferences` variable, and assign it the value of `differences.map()`. For the callback, return the value of `el` squared.
Оголосіть змінну `squaredDifferences` та призначте їй значення `differences.map()`. Щодо функції зворотного виклику: поверніть значення `el`, піднесене до квадрата.
# --hints--
@@ -31,13 +31,13 @@ assert.match(getVariance.toString(), /squaredDifferences\s*=\s*differences\.map\
assert.match(getVariance.toString(), /squaredDifferences\s*=\s*differences\.map\(function\s*\(?\s*el\s*\)?/);
```
Your `map` callback should return the value of `el` squared.
Функція зворотного виклику `map` повинна повернути значення `el`, піднесене до квадрата.
```js
assert.match(getVariance.toString(), /squaredDifferences\s*=\s*differences\.map\(function\s*\(?\s*el\s*\)?\s*\{\s*return\s*Math\.pow\(\s*el\s*,\s*2\s*\);\s*\}/);
```
Your `map` callback should use the `**` operator.
Функція зворотного виклику `map` повинна використовувати оператор `**`.
```js
assert.match(code.split("getVariance")[1], /el\s*\*\*\s*2/);
@@ -7,9 +7,9 @@ dashedName: step-40
# --description--
Next, you need to take the sum of the squared differences.
Далі потрібно знайти суму різниць, піднесених до квадрата.
Declare a `sumSquaredDifferences` variable, and assign it the value of `squaredDifferences.reduce()`. For the callback, return the sum of `acc` and `el`. Remember to set the initial value to `0`.
Оголосіть змінну `sumSquaredDifferences` та призначте їй значення `squaredDifferences.reduce()`. Щодо функції зворотного виклику: поверніть суму `acc` та `el`. Не забудьте встановити початкове значення `0`.
# --hints--
@@ -31,7 +31,7 @@ assert.match(getVariance.toString(), /sumSquaredDifferences\s*=\s*squaredDiffere
assert.match(getVariance.toString(), /sumSquaredDifferences\s*=\s*squaredDifferences\.reduce\(function\s*\(?\s*acc\s*,\s*el\s*\)?/);
```
Your `reduce` callback should return the sum of `acc` and `el`.
Функція зворотного виклику `reduce` повинна повернути суму `acc` та `el`.
```js
console.log(getVariance.toString());
@@ -7,9 +7,9 @@ dashedName: step-41
# --description--
With two `.map()` calls and a `.reduce()` call, you're creating extra arrays and iterating more times than needed. You should move all of the logic into the `.reduce()` call to save time and memory.
Завдяки двом викликам `.map()` й виклику `.reduce()` ви створюєте додаткові масиви та ітерація виконується більше, ніж потрібно. Вам потрібно перенести всю логіку до виклику `.reduce()`, щоб зберегти час та пам’ять.
Remove the `differences`, `squaredDifferences`, and `sumSquaredDifferences` variables (and their values). Declare a `variance` variable, and assign it the value of `array.reduce()`. For the callback, pass in your standard `acc` and `el` parameters, but leave the function body empty for now. Don't forget to set the initial value to `0`.
Вилучіть змінні `differences`, `squaredDifferences` та `sumSquaredDifferences` (і їхні значення). Оголосіть змінну `variance` та призначте їй значення `array.reduce()`. Щодо функції зворотного виклику: передайте стандартні параметри `acc` та `el`, але наразі залиште тіло функції порожнім. Не забудьте встановити початкове значення `0`.
# --hints--
@@ -49,13 +49,13 @@ assert.match(getVariance.toString(), /variance\s*=\s*array\.reduce\(/);
assert.match(getVariance.toString(), /variance\s*=\s*array\.reduce\(function\s*\(?\s*acc\s*,\s*el\s*\)?/);
```
Your `reduce` callback should be an empty function.
Функція зворотного виклику `reduce` повинна бути порожньою.
```js
assert.match(getVariance.toString(), /variance\s*=\s*array\.reduce\(function\s*\(?\s*acc\s*,\s*el\s*\)?\s*\{\s*\}/);
```
Your `reduce` callback should have an initial value of `0`.
Функція зворотного виклику `reduce` повинна мати початкове значення `0`.
```js
assert.match(getVariance.toString(), /variance\s*=\s*array\.reduce\(function\s*\(?\s*acc\s*,\s*el\s*\)?\s*\{\s*\}\s*,\s*0\s*\)/);
@@ -7,7 +7,7 @@ dashedName: step-42
# --description--
Within your empty `.reduce()` callback, declare a variable `difference` and set it to the value of `el` minus `mean`. Then declare a `squared` variable, and set it to the value of `difference` to the power of `2`. Finally, return the value of `acc` plus `squared`.
В межах порожньої функції зворотного виклику `.reduce()` оголосіть змінну `difference` та налаштуйте її значення на `el` мінус `mean`. Потім оголосіть змінну `squared` та налаштуйте її значення на `difference` у `2` степені. Вкінці поверніть значення `acc` плюс `squared`.
# --hints--
@@ -17,7 +17,7 @@ Within your empty `.reduce()` callback, declare a variable `difference` and set
assert.match(getVariance.toString(), /variance\s*=\s*array\.reduce\(function\s*\(?\s*acc\s*,\s*el\s*\)?\s*\{\s*var\s*difference\s*=/);
```
Your `difference` variable should be set to the value of `el` minus `mean`.
Змінна `difference` повинна мати значення `el` мінус `mean`.
```js
assert.match(getVariance.toString(), /variance\s*=\s*array\.reduce\(function\s*\(?\s*acc\s*,\s*el\s*\)?\s*\{\s*var\s*difference\s*=\s*el\s*-\s*mean\s*;/);
@@ -29,19 +29,19 @@ assert.match(getVariance.toString(), /variance\s*=\s*array\.reduce\(function\s*\
assert.match(getVariance.toString(), /variance\s*=\s*array\.reduce\(function\s*\(?\s*acc\s*,\s*el\s*\)?\s*\{\s*var\s*difference\s*=\s*el\s*-\s*mean\s*;\s*var\s*squared\s*=/);
```
Your `squared` variable should be set to the value of `difference` to the power of 2.
Змінна `squared` повинна мати значення `difference` у другому степені.
```js
assert.match(getVariance.toString(), /variance\s*=\s*array\.reduce\(function\s*\(?\s*acc\s*,\s*el\s*\)?\s*\{\s*var\s*difference\s*=\s*el\s*-\s*mean\s*;\s*var\s*squared\s*=\s*Math\.pow\(\s*difference\s*,\s*2\s*\);/);
```
Your `reduce` callback should return the value of `acc` plus `squared`.
Функція зворотного виклику `reduce` повинна повернути значення `acc` плюс `squared`.
```js
assert.match(getVariance.toString(), /variance\s*=\s*array\.reduce\(function\s*\(?\s*acc\s*,\s*el\s*\)?\s*\{\s*var\s*difference\s*=\s*el\s*-\s*mean\s*;\s*var\s*squared\s*=\s*Math\.pow\(\s*difference\s*,\s*2\s*\);\s*return\s*acc\s*\+\s*squared\s*;/);
```
You should not remove the initial value of `0` from your `.reduce()` method.
Не вилучайте початкове значення `0` з методу `.reduce()`.
```js
assert.match(getVariance.toString(), /variance\s*=\s*array\.reduce\(function\s*\(?\s*acc\s*,\s*el\s*\)?\s*\{\s*var\s*difference\s*=\s*el\s*-\s*mean\s*;\s*var\s*squared\s*=\s*Math\.pow\(\s*difference\s*,\s*2\s*\);\s*return\s*acc\s*\+\s*squared\s*;\s*\}\s*,\s*0\)/);

Some files were not shown because too many files have changed in this diff Show More