diff --git a/1-js/01-getting-started/4-devtools/article.md b/1-js/01-getting-started/4-devtools/article.md
index 325654993..d5cc32e17 100644
--- a/1-js/01-getting-started/4-devtools/article.md
+++ b/1-js/01-getting-started/4-devtools/article.md
@@ -49,12 +49,8 @@ Jejich vzhled je vcelku podobný. Až budete vědět, jak používat nástroje v
Safari (prohlížeč pro Mac, není podporován ve Windows nebo Linuxu) je v tomto ohledu trochu zvláštní. Nejprve musíme povolit „menu Vývoj“.
-<<<<<<< HEAD
-Otevřete „Preferences“ a jděte na záložku „Advanced“. Dole uvidíte checkbox, který zaškrtněte:
-=======
-Open Settings and go to the "Advanced" pane. There's a checkbox at the bottom:
->>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
-
+Otevřete „Settings“ a jděte na záložku „Advanced“. Dole uvidíte checkbox, který zaškrtněte:
+

Nyní můžete zapínat konzoli pomocí `key:Cmd+Opt+C`. Všimněte si také, že v horním menu se objevila nová položka s názvem „Develop“ („Vývoj“), která obsahuje mnoho příkazů a nastavení.
diff --git a/1-js/03-code-quality/05-testing-mocha/3-pow-test-wrong/solution.md b/1-js/03-code-quality/05-testing-mocha/3-pow-test-wrong/solution.md
index 4d0571b9d..fc2fe8146 100644
--- a/1-js/03-code-quality/05-testing-mocha/3-pow-test-wrong/solution.md
+++ b/1-js/03-code-quality/05-testing-mocha/3-pow-test-wrong/solution.md
@@ -1,50 +1,50 @@
-The test demonstrates one of the temptations a developer meets when writing tests.
+Tento test ukazuje jedno z pokušení, kterým vývojář při psaní testů čelí.
-What we have here is actually 3 tests, but layed out as a single function with 3 asserts.
+To, co zde máme, jsou ve skutečnosti 3 testy, ale jsou vytvořeny jako jediná funkce se 3 kontrolami.
-Sometimes it's easier to write this way, but if an error occurs, it's much less obvious what went wrong.
+Někdy je jednodušší psát takto, ale když nastane chyba, je mnohem méně zřejmé, co bylo špatně.
-If an error happens in the middle of a complex execution flow, then we'll have to figure out the data at that point. We'll actually have to *debug the test*.
+Nastane-li chyba uprostřed složitého provádění, musíme v té chvíli zjišťovat, jaká byla data. Vlastně musíme *ladit test*.
-It would be much better to break the test into multiple `it` blocks with clearly written inputs and outputs.
+Bylo by mnohem lepší rozdělit test do několika `it` bloků s jasně uvedenými vstupy a výstupy.
-Like this:
+Například takto:
```js
-describe("Raises x to power n", function() {
- it("5 in the power of 1 equals 5", function() {
- assert.equal(pow(5, 1), 5);
+describe("Umocní x na n-tou", function() {
+ it("5 na 1 se rovná 5", function() {
+ assert.equal(mocnina(5, 1), 5);
});
- it("5 in the power of 2 equals 25", function() {
- assert.equal(pow(5, 2), 25);
+ it("5 na 2 se rovná 25", function() {
+ assert.equal(mocnina(5, 2), 25);
});
- it("5 in the power of 3 equals 125", function() {
- assert.equal(pow(5, 3), 125);
+ it("5 na 3 se rovná 125", function() {
+ assert.equal(mocnina(5, 3), 125);
});
});
```
-We replaced the single `it` with `describe` and a group of `it` blocks. Now if something fails we would see clearly what the data was.
+Nahradili jsme jediné `it` za `describe` a skupinu `it` bloků. Když nyní něco selže, jasně uvidíme, jaká byla data.
-Also we can isolate a single test and run it in standalone mode by writing `it.only` instead of `it`:
+Nyní můžeme také izolovat jediný test a spustit jej samostatně. To uděláme tak, že napíšeme `it.only` místo `it`:
```js
-describe("Raises x to power n", function() {
- it("5 in the power of 1 equals 5", function() {
- assert.equal(pow(5, 1), 5);
+describe("Umocní x na n-tou", function() {
+ it("5 na 1 se rovná 5", function() {
+ assert.equal(mocnina(5, 1), 5);
});
*!*
- // Mocha will run only this block
- it.only("5 in the power of 2 equals 25", function() {
- assert.equal(pow(5, 2), 25);
+ // Mocha spustí pouze tento blok
+ it.only("5 na 2 se rovná 25", function() {
+ assert.equal(mocnina(5, 2), 25);
});
*/!*
- it("5 in the power of 3 equals 125", function() {
- assert.equal(pow(5, 3), 125);
+ it("5 na 3 se rovná 125", function() {
+ assert.equal(mocnina(5, 3), 125);
});
});
```
diff --git a/1-js/03-code-quality/05-testing-mocha/3-pow-test-wrong/task.md b/1-js/03-code-quality/05-testing-mocha/3-pow-test-wrong/task.md
index 66fece09a..41b26df3a 100644
--- a/1-js/03-code-quality/05-testing-mocha/3-pow-test-wrong/task.md
+++ b/1-js/03-code-quality/05-testing-mocha/3-pow-test-wrong/task.md
@@ -2,23 +2,23 @@ importance: 5
---
-# What's wrong in the test?
+# Co je na tomto testu špatně?
-What's wrong in the test of `pow` below?
+Co je špatně na níže uvedeném testu funkce `mocnina`?
```js
-it("Raises x to the power n", function() {
+it("Umocní x na n-tou", function() {
let x = 5;
- let result = x;
- assert.equal(pow(x, 1), result);
+ let výsledek = x;
+ assert.equal(mocnina(x, 1), výsledek);
- result *= x;
- assert.equal(pow(x, 2), result);
+ výsledek *= x;
+ assert.equal(mocnina(x, 2), výsledek);
- result *= x;
- assert.equal(pow(x, 3), result);
+ výsledek *= x;
+ assert.equal(mocnina(x, 3), výsledek);
});
```
-P.S. Syntactically the test is correct and passes.
+P.S. Syntakticky je tento test korektní a projde.
diff --git a/1-js/03-code-quality/05-testing-mocha/article.md b/1-js/03-code-quality/05-testing-mocha/article.md
index 4c2b1aa5e..d35aafd1c 100644
--- a/1-js/03-code-quality/05-testing-mocha/article.md
+++ b/1-js/03-code-quality/05-testing-mocha/article.md
@@ -1,279 +1,279 @@
-# Automated testing with Mocha
+# Automatické testování pomocí Mochy
-Automated testing will be used in further tasks, and it's also widely used in real projects.
+Automatické testování bude používáno v dalších úlohách a široce se používá i ve skutečných projektech.
-## Why do we need tests?
+## K čemu potřebujeme testy?
-When we write a function, we can usually imagine what it should do: which parameters give which results.
+Když píšeme funkci, můžeme si obvykle představit, co by měla dělat: jaké parametry by měly dávat jaké výsledky.
-During development, we can check the function by running it and comparing the outcome with the expected one. For instance, we can do it in the console.
+Během vývoje můžeme tuto funkci zkontrolovat tak, že ji spustíme a porovnáme její výsledek s očekávaným. Můžeme to udělat například na konzoli.
-If something is wrong -- then we fix the code, run again, check the result -- and so on till it works.
+Jestliže je něco špatně -- pak opravíme kód, znovu spustíme funkci, zkontrolujeme výsledek -- a tak dále, dokud to nebude fungovat.
-But such manual "re-runs" are imperfect.
+Avšak takové ruční „znovuspouštění“ není dokonalé.
-**When testing a code by manual re-runs, it's easy to miss something.**
+**Když testujeme kód tím, že ho znovu ručně spouštíme, můžeme snadno něco přehlédnout.**
-For instance, we're creating a function `f`. Wrote some code, testing: `f(1)` works, but `f(2)` doesn't work. We fix the code and now `f(2)` works. Looks complete? But we forgot to re-test `f(1)`. That may lead to an error.
+Například vytváříme funkci `f`. Napíšeme kód a testujeme: `f(1)` funguje, ale `f(2)` ne. Opravíme kód a nyní `f(2)` funguje. Vypadá to kompletně? Ale zapomněli jsme znovu otestovat `f(1)`. To může vést k chybě.
-That's very typical. When we develop something, we keep a lot of possible use cases in mind. But it's hard to expect a programmer to check all of them manually after every change. So it becomes easy to fix one thing and break another one.
+To je velmi typické. Když něco vyvíjíme, máme na paměti mnoho možných případů použití. Těžko však očekávat od programátora, že je po každé změně všechny znovu ručně prověří. Lehce se tedy stává, že opravíme jednu věc a rozbijeme jinou.
-**Automated testing means that tests are written separately, in addition to the code. They run our functions in various ways and compare results with the expected.**
+**Automatické testování znamená, že testy jsou psány odděleně navíc ke kódu. Různými způsoby spouštějí naše funkce a porovnávají jejich výsledky s očekávanými.**
-## Behavior Driven Development (BDD)
+## Vývoj řízený chováním (BDD)
-Let's start with a technique named [Behavior Driven Development](http://en.wikipedia.org/wiki/Behavior-driven_development) or, in short, BDD.
+Začněme technikou nazývanou *Vývoj řízený chováním*, anglicky [Behavior Driven Development](http://en.wikipedia.org/wiki/Behavior-driven_development), zkráceně BDD.
-**BDD is three things in one: tests AND documentation AND examples.**
+**BDD jsou tři věci v jedné: testy A dokumentace A příklady.**
-To understand BDD, we'll examine a practical case of development.
+Abychom BDD pochopili, prozkoumáme praktický příklad vývoje.
-## Development of "pow": the spec
+## Vývoj funkce „mocnina“: specifikace
-Let's say we want to make a function `pow(x, n)` that raises `x` to an integer power `n`. We assume that `n≥0`.
+Řekněme, že chceme vytvořit funkci `mocnina(x, n)`, která umocní `x` na celočíselný exponent `n`. Předpokládáme, že `n≥0`.
-That task is just an example: there's the `**` operator in JavaScript that can do that, but here we concentrate on the development flow that can be applied to more complex tasks as well.
+Tato úloha je jenom příklad: v JavaScriptu je operátor `**`, který to umí, ale zde se soustředíme na proces vývoje, který může být aplikován i na složitější úlohy.
-Before creating the code of `pow`, we can imagine what the function should do and describe it.
+Před vytvořením kódu funkce `mocnina` si představíme, co by tato funkce měla dělat, a popíšeme to.
-Such description is called a *specification* or, in short, a spec, and contains descriptions of use cases together with tests for them, like this:
+Takový popis se nazývá *specifikace* a obsahuje popisy případů použití společně s jejich testy, například takto:
```js
-describe("pow", function() {
+describe("mocnina", function() {
- it("raises to n-th power", function() {
- assert.equal(pow(2, 3), 8);
+ it("umocní na n-tou", function() {
+ assert.equal(mocnina(2, 3), 8);
});
});
```
-A spec has three main building blocks that you can see above:
+Specifikace má tři hlavní stavební bloky, které vidíte výše:
-`describe("title", function() { ... })`
-: What functionality we're describing? In our case we're describing the function `pow`. Used to group "workers" -- the `it` blocks.
+`describe("název", function() { ... })`
+: Jakou funkcionalitu popisujeme? V našem případě popisujeme funkci `mocnina`. Používá se k seskupení „pracovníků“ -- bloků `it`.
-`it("use case description", function() { ... })`
-: In the title of `it` we *in a human-readable way* describe the particular use case, and the second argument is a function that tests it.
+`it("popis případu použití", function() { ... })`
+: V titulku `it` popíšeme *lidsky čitelným způsobem* konkrétní případ použití. Druhým argumentem je funkce, která jej otestuje.
-`assert.equal(value1, value2)`
-: The code inside `it` block, if the implementation is correct, should execute without errors.
+`assert.equal(hodnota1, hodnota2)`
+: Je-li implementace korektní, kód uvnitř bloku `it` by se měl spustit bez chyb.
- Functions `assert.*` are used to check whether `pow` works as expected. Right here we're using one of them -- `assert.equal`, it compares arguments and yields an error if they are not equal. Here it checks that the result of `pow(2, 3)` equals `8`. There are other types of comparisons and checks, that we'll add later.
+Funkce `assert.*` se používají k ověření, zda `mocnina` funguje tak, jak očekáváme. Právě zde používáme jednu z nich -- `assert.equal`, která porovná argumenty a vyvolá chybu, pokud si nejsou rovny. Zde zkontroluje, zda výsledek `mocnina(2, 3)` se rovná `8`. Existují i jiné druhy porovnání a kontrol, které přidáme později.
-The specification can be executed, and it will run the test specified in `it` block. We'll see that later.
+Specifikaci můžeme spustit a ta pak spustí test specifikovaný v bloku `it`. To uvidíme později.
-## The development flow
+## Proces vývoje
-The flow of development usually looks like this:
+Proces vývoje obvykle vypadá takto:
-1. An initial spec is written, with tests for the most basic functionality.
-2. An initial implementation is created.
-3. To check whether it works, we run the testing framework [Mocha](https://mochajs.org/) (more details soon) that runs the spec. While the functionality is not complete, errors are displayed. We make corrections until everything works.
-4. Now we have a working initial implementation with tests.
-5. We add more use cases to the spec, probably not yet supported by the implementations. Tests start to fail.
-6. Go to 3, update the implementation till tests give no errors.
-7. Repeat steps 3-6 till the functionality is ready.
+1. Napíše se úvodní specifikace s testy pro většinu základní funkcionality.
+2. Vytvoří se úvodní implementace.
+3. Abychom prověřili, zda funguje, spustíme testovací rámec [Mocha](https://mochajs.org/) (více později), který spustí specifikaci. Dokud funkcionalita není úplná, budou se zobrazovat chyby. Provádíme opravy, dokud nebude vše fungovat.
+4. Nyní máme funkční úvodní implementaci s testy.
+5. Do specifikace přidáváme další případy použití, které implementace pravděpodobně ještě nepodporuje. Testy začnou selhávat.
+6. Vrátíme se ke kroku 3 a vylepšujeme implementaci, dokud testy nepřestanou vydávat chyby.
+7. Opakujeme kroky 3-6, dokud nebude funkcionalita připravena.
-So, the development is *iterative*. We write the spec, implement it, make sure tests pass, then write more tests, make sure they work etc. At the end we have both a working implementation and tests for it.
+Vývoj je tedy *iterativní*. Napíšeme specifikaci, implementujeme ji, ujistíme se, že testy projdou, napíšeme další testy, ujistíme se, že projdou, atd. Nakonec máme funkční implementaci i její testy.
-Let's see this development flow in our practical case.
+Podívejme se na tento proces vývoje v praxi.
-The first step is already complete: we have an initial spec for `pow`. Now, before making the implementation, let's use a few JavaScript libraries to run the tests, just to see that they are working (they will all fail).
+První krok je již téměř hotov: máme úvodní specifikaci funkce `mocnina`. Nyní před vytvořením implementace použijeme několik JavaScriptových knihoven ke spuštění testů, abychom viděli, zda fungují (všechny testy selžou).
-## The spec in action
+## Specifikace v akci
-Here in the tutorial we'll be using the following JavaScript libraries for tests:
+V tomto tutoriálu budeme pro testy používat následující JavaScriptové knihovny:
-- [Mocha](https://mochajs.org/) -- the core framework: it provides common testing functions including `describe` and `it` and the main function that runs tests.
-- [Chai](https://www.chaijs.com/) -- the library with many assertions. It allows to use a lot of different assertions, for now we need only `assert.equal`.
-- [Sinon](https://sinonjs.org/) -- a library to spy over functions, emulate built-in functions and more, we'll need it much later.
+- [Mocha](https://mochajs.org/) -- jádro rámce: poskytuje běžné testovací funkce včetně `describe` a `it` a hlavní funkci, která spouští testy.
+- [Chai](https://www.chaijs.com/) -- knihovna s mnoha kontrolami. Umožňuje nám použít spoustu různých kontrol, ale nyní budeme potřebovat jen `assert.equal`.
+- [Sinon](https://sinonjs.org/) -- knihovna k prozkoumávání funkcí, emulování vestavěných funkcí a podobně. Budeme ji potřebovat až mnohem později.
-These libraries are suitable for both in-browser and server-side testing. Here we'll consider the browser variant.
+Tyto knihovny jsou vhodné pro testování v prohlížeči i na straně serveru. Zde budeme uvažovat prohlížečovou variantu.
-The full HTML page with these frameworks and `pow` spec:
+Celá HTML stránka s těmito rámci a specifikací funkce `mocnina`:
```html src="https://github.com/index.html"
```
-The page can be divided into five parts:
+Tuto stránku lze rozdělit do pěti částí:
-1. The `
- Context: { x: 2, n: 3, at line 1 }
- pow(2, 3)
+ Kontext: { x: 2, n: 3, na řádku 1 }
+ mocnina(2, 3)
-That's when the function starts to execute. The condition `n == 1` is falsy, so the flow continues into the second branch of `if`:
+Na tomto místě začne výkon funkce. Podmínka `n == 1` není splněna, takže řízení pokračuje druhou větví `if`:
```js run
-function pow(x, n) {
+function mocnina(x, n) {
if (n == 1) {
return x;
} else {
*!*
- return x * pow(x, n - 1);
+ return x * mocnina(x, n - 1);
*/!*
}
}
-alert( pow(2, 3) );
+alert( mocnina(2, 3) );
```
-The variables are same, but the line changes, so the context is now:
+Proměnné jsou stejné, ale řádek se změní, takže kontext nyní je:
- Context: { x: 2, n: 3, at line 5 }
- pow(2, 3)
+ Kontext: { x: 2, n: 3, na řádku 5 }
+ mocnina(2, 3)
-To calculate `x * pow(x, n - 1)`, we need to make a subcall of `pow` with new arguments `pow(2, 2)`.
+K výpočtu `x * mocnina(x, n - 1)` musíme učinit vnořené volání funkce `mocnina` s novými argumenty: `mocnina(2, 2)`.
-### pow(2, 2)
+### mocnina(2, 2)
-To do a nested call, JavaScript remembers the current execution context in the *execution context stack*.
+Aby JavaScript mohl provést vnořené volání, zapamatuje si aktuální prováděcí kontext v *zásobníku prováděcích kontextů*.
-Here we call the same function `pow`, but it absolutely doesn't matter. The process is the same for all functions:
+Zde voláme stejnou funkci `mocnina`, ale na tom vůbec nezáleží. Proces je pro všechny funkce stejný:
-1. The current context is "remembered" on top of the stack.
-2. The new context is created for the subcall.
-3. When the subcall is finished -- the previous context is popped from the stack, and its execution continues.
+1. Aktuální kontext se uloží na vrchol zásobníku.
+2. Pro vnořené volání se vytvoří nový kontext.
+3. Až bude vnořené volání ukončeno, předchozí kontext se vyjme ze zásobníku a jeho vykonávání bude pokračovat.
-Here's the context stack when we entered the subcall `pow(2, 2)`:
+Takto vypadá zásobník kontextů ve chvíli, kdy jsme vstoupili do vnořeného volání `mocnina(2, 2)`:
- Context: { x: 2, n: 2, at line 1 }
- pow(2, 2)
+ Kontext: { x: 2, n: 2, na řádku 1 }
+ mocnina(2, 2)
- Context: { x: 2, n: 3, at line 5 }
- pow(2, 3)
+ Kontext: { x: 2, n: 3, na řádku 5 }
+ mocnina(2, 3)
-The new current execution context is on top (and bold), and previous remembered contexts are below.
+Nový aktuální prováděcí kontext je na vrcholu (a uveden tučně), předchozí uložené kontexty jsou níže.
-When we finish the subcall -- it is easy to resume the previous context, because it keeps both variables and the exact place of the code where it stopped.
+Až vnořené volání skončí, bude snadné obnovit předchozí kontext, jelikož ten si pamatuje obě proměnné i přesné místo kódu, na němž se zastavil.
```smart
-Here in the picture we use the word "line", as in our example there's only one subcall in line, but generally a single line of code may contain multiple subcalls, like `pow(…) + pow(…) + somethingElse(…)`.
+Na tomto obrázku používáme slovo „řádek“, protože v našem příkladu je na řádku jen jediné volání, ale obecně jeden řádek kódu může obsahovat několik volání, například `mocnina(…) + mocnina(…) + něcoJiného(…)`.
-So it would be more precise to say that the execution resumes "immediately after the subcall".
+Bylo by tedy přesnější říkat, že provádění se obnoví „ihned za vnořeným voláním“.
```
-### pow(2, 1)
+### mocnina(2, 1)
-The process repeats: a new subcall is made at line `5`, now with arguments `x=2`, `n=1`.
+Proces se opakuje: na řádku `5` se učiní nové vnořené volání, tentokrát s argumenty `x=2`, `n=1`.
-A new execution context is created, the previous one is pushed on top of the stack:
+Vytvoří se nový prováděcí kontext, předchozí se uloží na vrchol zásobníku:
- Context: { x: 2, n: 1, at line 1 }
- pow(2, 1)
+ Kontext: { x: 2, n: 1, na řádku 1 }
+ mocnina(2, 1)
- Context: { x: 2, n: 2, at line 5 }
- pow(2, 2)
+ Kontext: { x: 2, n: 2, na řádku 5 }
+ mocnina(2, 2)
- Context: { x: 2, n: 3, at line 5 }
- pow(2, 3)
+ Kontext: { x: 2, n: 3, na řádku 5 }
+ mocnina(2, 3)
-There are 2 old contexts now and 1 currently running for `pow(2, 1)`.
+Nyní máme 2 staré kontexty a 1 právě probíhající pro `mocnina(2, 1)`.
-### The exit
+### Konec
-During the execution of `pow(2, 1)`, unlike before, the condition `n == 1` is truthy, so the first branch of `if` works:
+Během provádění `mocnina(2, 1)` je na rozdíl od předchozích případů podmínka `n == 1` splněna, takže bude provedena první větev `if`:
```js
-function pow(x, n) {
+function mocnina(x, n) {
if (n == 1) {
*!*
return x;
*/!*
} else {
- return x * pow(x, n - 1);
+ return x * mocnina(x, n - 1);
}
}
```
-There are no more nested calls, so the function finishes, returning `2`.
-
-As the function finishes, its execution context is not needed anymore, so it's removed from the memory. The previous one is restored off the top of the stack:
+Další vnořená volání už nejsou, takže funkce skončí a vrátí `2`.
+Až funkce skončí, její prováděcí kontext už nebude zapotřebí, takže bude odstraněn z paměti. Na vrcholu zásobníku se obnoví předchozí prováděcí kontext:
- Context: { x: 2, n: 2, at line 5 }
- pow(2, 2)
+ Kontext: { x: 2, n: 2, na řádku 5 }
+ mocnina(2, 2)
- Context: { x: 2, n: 3, at line 5 }
- pow(2, 3)
+ Kontext: { x: 2, n: 3, na řádku 5 }
+ mocnina(2, 3)
-The execution of `pow(2, 2)` is resumed. It has the result of the subcall `pow(2, 1)`, so it also can finish the evaluation of `x * pow(x, n - 1)`, returning `4`.
+Obnoví se provádění `mocnina(2, 2)`. To zná výsledek vnořeného volání `mocnina(2, 1)`, takže může dokončit výpočet `x * mocnina(x, n - 1)` a vrátit `4`.
-Then the previous context is restored:
+Pak se obnoví předchozí kontext:
- Context: { x: 2, n: 3, at line 5 }
- pow(2, 3)
+ Kontext: { x: 2, n: 3, na řádku 5 }
+ mocnina(2, 3)
-When it finishes, we have a result of `pow(2, 3) = 8`.
+Až skončí, budeme mít výsledek `mocnina(2, 3) = 8`.
-The recursion depth in this case was: **3**.
+Hloubka rekurze v tomto případě byla **3**.
-As we can see from the illustrations above, recursion depth equals the maximal number of context in the stack.
+Jak vidíme z výše uvedených ilustrací, hloubka rekurze se rovná nejvyššímu počtu kontextů v zásobníku.
-Note the memory requirements. Contexts take memory. In our case, raising to the power of `n` actually requires the memory for `n` contexts, for all lower values of `n`.
+Všimněte si paměťových požadavků. Kontexty zabírají paměť. V našem případě umocnění na `n`-tou ve skutečnosti vyžaduje paměť pro `n` kontextů, jeden pro každou nižší hodnotu `n`.
-A loop-based algorithm is more memory-saving:
+Algoritmus založený na cyklu ušetří více paměti:
```js
-function pow(x, n) {
- let result = 1;
+function mocnina(x, n) {
+ let výsledek = 1;
for (let i = 0; i < n; i++) {
- result *= x;
+ výsledek *= x;
}
- return result;
+ return výsledek;
}
```
-The iterative `pow` uses a single context changing `i` and `result` in the process. Its memory requirements are small, fixed and do not depend on `n`.
+Iterativní `mocnina` používá jediný kontext, v jehož procesu se mění `i` a `výsledek`. Její paměťové požadavky jsou malé, pevné a nezávisejí na velikosti `n`.
-**Any recursion can be rewritten as a loop. The loop variant usually can be made more effective.**
+**Každou rekurzi lze přepsat do cyklu. Variantu s cyklem lze obvykle napsat efektivněji.**
-...But sometimes the rewrite is non-trivial, especially when a function uses different recursive subcalls depending on conditions and merges their results or when the branching is more intricate. And the optimization may be unneeded and totally not worth the efforts.
+...Toto přepsání však někdy není triviální, zvláště když funkce používá různá rekurzívní volání v závislosti na podmínkách a spojuje jejich výsledky, nebo když je větvení složitější. A optimalizace může být nepotřebná a nemusí vůbec stát za vynaloženou námahu.
-Recursion can give a shorter code, easier to understand and support. Optimizations are not required in every place, mostly we need a good code, that's why it's used.
+Rekurze mohou vydat kratší kód, jednodušší na porozumění a údržbu. Optimalizace nejsou nutné všude, většinou potřebujeme dobrý kód, proto používáme rekurzi.
-## Recursive traversals
+## Rekurzívní traverzování
-Another great application of the recursion is a recursive traversal.
+Další skvělé využití rekurze je rekurzívní traverzování.
-Imagine, we have a company. The staff structure can be presented as an object:
+Představme si, že máme firmu. Struktura jejího personálu se dá vyjádřit jako objekt:
```js
-let company = {
- sales: [{
- name: 'John',
- salary: 1000
+let firma = {
+ prodeje: [{
+ jméno: 'Jan',
+ plat: 1000
}, {
- name: 'Alice',
- salary: 1600
+ jméno: 'Alice',
+ plat: 1600
}],
- development: {
- sites: [{
- name: 'Peter',
- salary: 2000
+ vývoj: {
+ pobočky: [{
+ jméno: 'Petr',
+ plat: 2000
}, {
- name: 'Alex',
- salary: 1800
+ jméno: 'Aleš',
+ plat: 1800
}],
- internals: [{
- name: 'Jack',
- salary: 1300
+ interní: [{
+ jméno: 'Kuba',
+ plat: 1300
}]
}
};
```
-In other words, a company has departments.
+Jinými slovy, firma má různá oddělení.
-- A department may have an array of staff. For instance, `sales` department has 2 employees: John and Alice.
-- Or a department may split into subdepartments, like `development` has two branches: `sites` and `internals`. Each of them has their own staff.
-- It is also possible that when a subdepartment grows, it divides into subsubdepartments (or teams).
+- Oddělení může mít pole zaměstnanců. Například oddělení `prodeje` má 2 zaměstnance: Jana a Alici.
+- Nebo se oddělení může větvit na nižší oddělení, například `vývoj` má dvě větve: `pobočky` a `interní`. Každá z nich má své vlastní zaměstnance.
+- Je také možné, že když se nižší oddělení rozroste, rozdělí se na ještě nižší oddělení (nebo týmy).
- For instance, the `sites` department in the future may be split into teams for `siteA` and `siteB`. And they, potentially, can split even more. That's not on the picture, just something to have in mind.
+ Například oddělení `pobočky` se v budoucnu může rozdělit na týmy pro `pobočkaA` a `pobočkaB`. A ty se mohou rozdělit ještě dál. To není na obrázku, je to jen něco, co musíme mít na paměti.
-Now let's say we want a function to get the sum of all salaries. How can we do that?
+Nyní řekněme, že chceme funkci, která vrátí součet všech platů. Jak ji můžeme napsat?
-An iterative approach is not easy, because the structure is not simple. The first idea may be to make a `for` loop over `company` with nested subloop over 1st level departments. But then we need more nested subloops to iterate over the staff in 2nd level departments like `sites`... And then another subloop inside those for 3rd level departments that might appear in the future? If we put 3-4 nested subloops in the code to traverse a single object, it becomes rather ugly.
+Iterativní přístup není snadný, protože struktura není jednoduchá. První myšlenkou může být vytvořit cyklus `for` nad objektem `firma` s vnořeným podcyklem nad odděleními 1. úrovně. Pak ale budeme potřebovat další vnořené podcykly, které budou iterovat nad personálem oddělení 2. úrovně, jako je `pobočky`... A v nich pak další podcyklus pro oddělení 3. úrovně, která se mohou objevit v budoucnu? Jestliže do kódu vložíme 3-4 vnořené podcykly, aby procházely jediný objekt, bude to poměrně ošklivé.
-Let's try recursion.
+Zkusme rekurzi.
-As we can see, when our function gets a department to sum, there are two possible cases:
+Jak vidíme, když naše funkce obdrží oddělení, jehož platy má sečíst, mohou nastat dva případy:
-1. Either it's a "simple" department with an *array* of people -- then we can sum the salaries in a simple loop.
-2. Or it's *an object* with `N` subdepartments -- then we can make `N` recursive calls to get the sum for each of the subdeps and combine the results.
+1. Buď je to „jednoduché“ oddělení s *polem* zaměstnanců -- pak můžeme sečíst jejich platy v jediném cyklu.
+2. Nebo je to *objekt* s `N` podřízenými odděleními -- pak můžeme učinit `N` rekurzívních volání, abychom získali součet pro každé nižší oddělení, a zkombinovat výsledky.
-The 1st case is the base of recursion, the trivial case, when we get an array.
+První případ je základem rekurze, triviální případ, když obdržíme pole.
-The 2nd case when we get an object is the recursive step. A complex task is split into subtasks for smaller departments. They may in turn split again, but sooner or later the split will finish at (1).
+Druhý případ, když obdržíme objekt, je rekurzívní krok. Složitý úkol rozdělíme na podúkoly pro menší oddělení. Ta se pak mohou opět rozdělit, ale dříve nebo později dělení skončí případem (1).
-The algorithm is probably even easier to read from the code:
+Algoritmus je pravděpodobně ještě snadnější vyčíst z kódu:
```js run
-let company = { // the same object, compressed for brevity
- sales: [{name: 'John', salary: 1000}, {name: 'Alice', salary: 1600 }],
- development: {
- sites: [{name: 'Peter', salary: 2000}, {name: 'Alex', salary: 1800 }],
- internals: [{name: 'Jack', salary: 1300}]
+let firma = { // stejný objekt, zkomprimovaný pro stručnost
+ platy: [{jméno: 'Jan', plat: 1000}, {jméno: 'Alice', plat: 1600 }],
+ vývoj: {
+ pobočky: [{jméno: 'Petr', plat: 2000}, {jméno: 'Aleš', plat: 1800 }],
+ interní: [{jméno: 'Kuba', plat: 1300}]
}
};
-// The function to do the job
+// Funkce, která odvede práci
*!*
-function sumSalaries(department) {
- if (Array.isArray(department)) { // case (1)
- return department.reduce((prev, current) => prev + current.salary, 0); // sum the array
- } else { // case (2)
- let sum = 0;
- for (let subdep of Object.values(department)) {
- sum += sumSalaries(subdep); // recursively call for subdepartments, sum the results
+function sečtiPlaty(oddělení) {
+ if (Array.isArray(oddělení)) { // případ (1)
+ return oddělení.reduce((předchozí, aktuální) => předchozí + aktuální.plat, 0); // sečteme pole
+ } else { // případ (2)
+ let součet = 0;
+ for (let pododdělení of Object.values(oddělení)) {
+ součet += sečtiPlaty(pododdělení); // rekurzívní volání pro nižší oddělení, sečteme výsledky
}
- return sum;
+ return součet;
}
}
*/!*
-alert(sumSalaries(company)); // 7700
+alert(sečtiPlaty(firma)); // 7700
```
-The code is short and easy to understand (hopefully?). That's the power of recursion. It also works for any level of subdepartment nesting.
+Kód je krátký a snadno srozumitelný (doufejme?). V tom spočívá síla rekurze. Navíc funguje pro jakoukoli úroveň vnoření oddělení.
-Here's the diagram of calls:
+Zde je diagram volání:
-
+
-We can easily see the principle: for an object `{...}` subcalls are made, while arrays `[...]` are the "leaves" of the recursion tree, they give immediate result.
+Snadno vidíme princip: pro objekty `{...}` se učiní volání, zatímco pole `[...]` jsou „listy“ rekurzívního stromu a dávají okamžitý výsledek.
-Note that the code uses smart features that we've covered before:
+Všimněte si, že kód využívá elegantní prvky, které jsme uvedli již dříve:
-- Method `arr.reduce` explained in the chapter to get the sum of the array.
-- Loop `for(val of Object.values(obj))` to iterate over object values: `Object.values` returns an array of them.
+- Metodu `pole.reduce` vysvětlenou v kapitole k získání součtu pole.
+- Cyklus `for(hodnota of Object.values(obj))` k iteraci nad hodnotami objektu: `Object.values` vrací jejich pole.
-## Recursive structures
+## Rekurzívní struktury
-A recursive (recursively-defined) data structure is a structure that replicates itself in parts.
+Rekurzívní (rekurzívně definovaná) datová struktura je struktura, která částečně replikuje sama sebe.
-We've just seen it in the example of a company structure above.
+Ve výše uvedeném příkladu struktury firmy jsme ji právě viděli.
-A company *department* is:
-- Either an array of people.
-- Or an object with *departments*.
+Firemní *oddělení* je:
+- buď pole lidí,
+- nebo objekt s *odděleními*.
-For web-developers there are much better-known examples: HTML and XML documents.
+Pro vývojáře webů existují mnohem lépe známé příklady: HTML a XML dokumenty.
-In the HTML document, an *HTML-tag* may contain a list of:
-- Text pieces.
-- HTML-comments.
-- Other *HTML-tags* (that in turn may contain text pieces/comments or other tags etc).
+V HTML dokumentu může *HTML značka (tag)* obsahovat seznam:
+- úryvků textu,
+- HTML komentářů,
+- jiných *HTML značek* (které mohou opět obsahovat úryvky textu, komentáře nebo jiné značky atd.).
-That's once again a recursive definition.
+To je opět rekurzívní definice.
-For better understanding, we'll cover one more recursive structure named "Linked list" that might be a better alternative for arrays in some cases.
+Pro lepší porozumění uvedeme ještě jednu rekurzívní strukturu nazývanou „spojový seznam“, která by v některých případech mohla být lepší alternativou k polím.
-### Linked list
+### Spojový seznam
-Imagine, we want to store an ordered list of objects.
+Představme si, že si chceme uložit seřazený seznam objektů.
-The natural choice would be an array:
+Přirozenou volbou by bylo pole:
```js
-let arr = [obj1, obj2, obj3];
+let pole = [obj1, obj2, obj3];
```
-...But there's a problem with arrays. The "delete element" and "insert element" operations are expensive. For instance, `arr.unshift(obj)` operation has to renumber all elements to make room for a new `obj`, and if the array is big, it takes time. Same with `arr.shift()`.
+...S poli je však problém. Operace „smazání prvku“ a „vložení prvku“ jsou nákladné. Například operace `pole.unshift(obj)` musí přečíslovat všechny prvky, aby uvolnila místo pro nový objekt `obj`, a je-li pole velké, zabere to čas. Totéž platí pro `pole.shift()`.
-The only structural modifications that do not require mass-renumbering are those that operate with the end of array: `arr.push/pop`. So an array can be quite slow for big queues, when we have to work with the beginning.
+Jediné strukturální modifikace nevyžadující masové přečíslování jsou ty, které pracují s koncem pole: `pole.push/pop`. Pro velké fronty tedy pole může být poměrně pomalé, musíme-li pracovat s jeho začátkem.
-Alternatively, if we really need fast insertion/deletion, we can choose another data structure called a [linked list](https://en.wikipedia.org/wiki/Linked_list).
+Alternativně, jestliže potřebujeme opravdu rychlé vkládání a mazání, si můžeme zvolit jinou datovou strukturu nazvanou [lineární spojový seznam](https://cs.wikipedia.org/wiki/Lineární_seznam).
-The *linked list element* is recursively defined as an object with:
-- `value`.
-- `next` property referencing the next *linked list element* or `null` if that's the end.
+*Prvek spojového seznamu* je rekurzívně definován jako objekt, který obsahuje:
+- hodnotu `hodnota`.
+- vlastnost `další`, která se odkazuje na další *prvek spojového seznamu* nebo, jestliže tento prvek je poslední, je rovna `null`.
-For instance:
+Příklad:
```js
-let list = {
- value: 1,
- next: {
- value: 2,
- next: {
- value: 3,
- next: {
- value: 4,
- next: null
+let seznam = {
+ hodnota: 1,
+ další: {
+ hodnota: 2,
+ další: {
+ hodnota: 3,
+ další: {
+ hodnota: 4,
+ další: null
}
}
}
};
```
-Graphical representation of the list:
+Grafické zobrazení seznamu:
-
+
-An alternative code for creation:
+Alternativní kód pro vytvoření:
```js no-beautify
-let list = { value: 1 };
-list.next = { value: 2 };
-list.next.next = { value: 3 };
-list.next.next.next = { value: 4 };
-list.next.next.next.next = null;
+let seznam = { hodnota: 1 };
+seznam.další = { hodnota: 2 };
+seznam.další.další = { hodnota: 3 };
+seznam.další.další.další = { hodnota: 4 };
+seznam.další.další.další.další = null;
```
-Here we can even more clearly see that there are multiple objects, each one has the `value` and `next` pointing to the neighbour. The `list` variable is the first object in the chain, so following `next` pointers from it we can reach any element.
+Tady můžeme jasně vidět, že zde je více objektů, každý z nich má hodnotu `hodnota` a prvek `další`, který ukazuje na souseda. Proměnná `seznam` je první objekt v řetězci, takže pomocí ukazatelů `další` se z ní můžeme dostat na kterýkoli prvek.
-The list can be easily split into multiple parts and later joined back:
+Seznam můžeme snadno rozdělit na více částí a pak znovu spojit:
```js
-let secondList = list.next.next;
-list.next.next = null;
+let druhýSeznam = seznam.další.další;
+seznam.další.další = null;
```
-
+
-To join:
+Spojení:
```js
-list.next.next = secondList;
+seznam.další.další = druhýSeznam;
```
-And surely we can insert or remove items in any place.
+A samozřejmě můžeme na kterémkoli místě vkládat nebo odstraňovat prvky.
-For instance, to prepend a new value, we need to update the head of the list:
+Například chceme-li přidat novou hodnotu na začátek seznamu, musíme změnit jeho hlavičku:
```js
-let list = { value: 1 };
-list.next = { value: 2 };
-list.next.next = { value: 3 };
-list.next.next.next = { value: 4 };
+let seznam = { hodnota: 1 };
+seznam.další = { hodnota: 2 };
+seznam.další.další = { hodnota: 3 };
+seznam.další.další.další = { hodnota: 4 };
*!*
-// prepend the new value to the list
-list = { value: "new item", next: list };
+// připojíme novou hodnotu na začátek seznamu
+seznam = { hodnota: "nový prvek", další: seznam };
*/!*
```
-
+
-To remove a value from the middle, change `next` of the previous one:
+Abychom odstranili prvek uprostřed, změníme `další` u předchozího prvku:
```js
-list.next = list.next.next;
+seznam.další = seznam.další.další;
```

-We made `list.next` jump over `1` to value `2`. The value `1` is now excluded from the chain. If it's not stored anywhere else, it will be automatically removed from the memory.
+Způsobili jsme, že `seznam.další` bude přeskakovat `1` rovnou na hodnotu `2`. Hodnota `1` je nyní z řetězce vyřazena. Pokud není uložena někde jinde, bude automaticky odstraněna z paměti.
-Unlike arrays, there's no mass-renumbering, we can easily rearrange elements.
+Na rozdíl od polí zde nedochází k masovému přečíslování, takže můžeme prvky snadno přeskupovat.
-Naturally, lists are not always better than arrays. Otherwise everyone would use only lists.
+Pochopitelně seznamy nejsou vždy lepší než pole, jinak by všichni používali jedině seznamy.
-The main drawback is that we can't easily access an element by its number. In an array that's easy: `arr[n]` is a direct reference. But in the list we need to start from the first item and go `next` `N` times to get the Nth element.
+Jejich hlavní nevýhodou je, že nemůžeme snadno přistupovat k prvku podle jeho čísla. V poli je to jednoduché: `pole[n]` je přímý odkaz. Ale v seznamu musíme začít od prvního prvku a jít na `další` celkem `N`-krát, abychom získali N-tý prvek.
-...But we don't always need such operations. For instance, when we need a queue or even a [deque](https://en.wikipedia.org/wiki/Double-ended_queue) -- the ordered structure that must allow very fast adding/removing elements from both ends, but access to its middle is not needed.
+...Takové operace však nepotřebujeme vždy. Například když potřebujeme frontu nebo dokonce [frontu s dvojitým koncem](https://en.wikipedia.org/wiki/Double-ended_queue) -- seřazenou strukturu, která musí umožňovat velmi rychlé přidávání a odstraňování prvků z obou konců, ale přístup doprostřed není nutný.
-Lists can be enhanced:
-- We can add property `prev` in addition to `next` to reference the previous element, to move back easily.
-- We can also add a variable named `tail` referencing the last element of the list (and update it when adding/removing elements from the end).
-- ...The data structure may vary according to our needs.
+Seznamy můžeme vylepšit:
+- Můžeme navíc k vlastnosti `další` přidat vlastnost `předchozí`, která bude odkazovat na předchozí prvek, abychom se mohli snadno vracet zpět.
+- Můžeme také přidat proměnnou `konec` odkazující se na poslední prvek seznamu (a aktualizovat ji, když budeme přidávat nebo odebírat prvky z konce).
+- ...Tato datová struktura se může lišit podle našich potřeb.
-## Summary
+## Shrnutí
-Terms:
-- *Recursion* is a programming term that means calling a function from itself. Recursive functions can be used to solve tasks in elegant ways.
+Pojmy:
+- *Rekurze* je programátorský pojem, který znamená volání funkce sebou samotnou. Pomocí rekurzívních funkcí můžeme řešit úlohy elegantním způsobem.
- When a function calls itself, that's called a *recursion step*. The *basis* of recursion is function arguments that make the task so simple that the function does not make further calls.
+ Volání funkce sebou samotnou se nazývá *rekurzívní krok*. *Základ* rekurze jsou funkční argumenty, s nimiž je úloha natolik jednoduchá, že funkce už neučiní další volání.
-- A [recursively-defined](https://en.wikipedia.org/wiki/Recursive_data_type) data structure is a data structure that can be defined using itself.
+- [Rekurzívně definovaná](https://en.wikipedia.org/wiki/Recursive_data_type) datová struktura je datová struktura, která může být definována pomocí sebe sama.
- For instance, the linked list can be defined as a data structure consisting of an object referencing a list (or null).
+ Například spojový seznam může být definován jako datová struktura, která se skládá z objektu odkazujícího se na seznam (nebo null).
```js
- list = { value, next -> list }
+ seznam = { hodnota, další -> seznam }
```
- Trees like HTML elements tree or the department tree from this chapter are also naturally recursive: they have branches and every branch can have other branches.
+ Stromy jako strom HTML prvků nebo strom firemních oddělení z této kapitoly jsou rovněž přirozeně rekurzívní: obsahují větve a každá větev může obsahovat další větve.
- Recursive functions can be used to walk them as we've seen in the `sumSalary` example.
+ K jejich procházení mohou být použity rekurzívní funkce, jak jsme viděli v příkladu `sečtiPlaty`.
-Any recursive function can be rewritten into an iterative one. And that's sometimes required to optimize stuff. But for many tasks a recursive solution is fast enough and easier to write and support.
+Každou rekurzívní funkci můžeme přepsat na iterativní. Někdy je to nutné kvůli optimalizaci. Pro mnoho úloh je však rekurzívní řešení dostatečně rychlé a snadnější na napsání i údržbu.
diff --git a/1-js/06-advanced-functions/01-recursion/linked-list-0.svg b/1-js/06-advanced-functions/01-recursion/linked-list-0.svg
index 5d23c7a4c..d3c552d8c 100644
--- a/1-js/06-advanced-functions/01-recursion/linked-list-0.svg
+++ b/1-js/06-advanced-functions/01-recursion/linked-list-0.svg
@@ -1 +1,272 @@
-
\ No newline at end of file
+
+
diff --git a/1-js/06-advanced-functions/01-recursion/linked-list-remove-1.svg b/1-js/06-advanced-functions/01-recursion/linked-list-remove-1.svg
index 2f37449c4..46ef2a82a 100644
--- a/1-js/06-advanced-functions/01-recursion/linked-list-remove-1.svg
+++ b/1-js/06-advanced-functions/01-recursion/linked-list-remove-1.svg
@@ -1 +1,277 @@
-
\ No newline at end of file
+
+
diff --git a/1-js/06-advanced-functions/01-recursion/linked-list-split.svg b/1-js/06-advanced-functions/01-recursion/linked-list-split.svg
index 6c3072130..175895c35 100644
--- a/1-js/06-advanced-functions/01-recursion/linked-list-split.svg
+++ b/1-js/06-advanced-functions/01-recursion/linked-list-split.svg
@@ -1 +1,250 @@
-
\ No newline at end of file
+
+
diff --git a/1-js/06-advanced-functions/01-recursion/linked-list.svg b/1-js/06-advanced-functions/01-recursion/linked-list.svg
index c02744f39..746e5811c 100644
--- a/1-js/06-advanced-functions/01-recursion/linked-list.svg
+++ b/1-js/06-advanced-functions/01-recursion/linked-list.svg
@@ -1 +1,232 @@
-
\ No newline at end of file
+
+
diff --git a/1-js/06-advanced-functions/01-recursion/recursion-pow.svg b/1-js/06-advanced-functions/01-recursion/recursion-pow.svg
index 2b970a04a..a7c4e3ebb 100644
--- a/1-js/06-advanced-functions/01-recursion/recursion-pow.svg
+++ b/1-js/06-advanced-functions/01-recursion/recursion-pow.svg
@@ -1 +1,203 @@
-
\ No newline at end of file
+
+
diff --git a/1-js/06-advanced-functions/02-rest-parameters-spread/article.md b/1-js/06-advanced-functions/02-rest-parameters-spread/article.md
index dbdfbd6c0..eda7780b6 100644
--- a/1-js/06-advanced-functions/02-rest-parameters-spread/article.md
+++ b/1-js/06-advanced-functions/02-rest-parameters-spread/article.md
@@ -1,295 +1,294 @@
-# Rest parameters and spread syntax
+# Zbytkové parametry a roztažená syntaxe
-Many JavaScript built-in functions support an arbitrary number of arguments.
+Mnoho vestavěných funkcí v JavaScriptu umožňuje uvést libovolný počet argumentů.
-For instance:
+Například:
-- `Math.max(arg1, arg2, ..., argN)` -- returns the greatest of the arguments.
-- `Object.assign(dest, src1, ..., srcN)` -- copies properties from `src1..N` into `dest`.
-- ...and so on.
+- `Math.max(arg1, arg2, ..., argN)` -- vrátí největší z argumentů.
+- `Object.assign(cíl, zdroj1, ..., zdrojN)` -- zkopíruje vlastnosti ze `zdroj1..N` do `cíl`.
+- ...a tak dále.
-In this chapter we'll learn how to do the same. And also, how to pass arrays to such functions as parameters.
+V této kapitole se naučíme, jak udělat totéž, a také, jak předávat do takových funkcí pole jako parametry.
-## Rest parameters `...`
+## Zbytkové parametry `...`
-A function can be called with any number of arguments, no matter how it is defined.
+Funkci můžeme volat s libovolným počtem argumentů, bez ohledu na to, jak je definována.
-Like here:
+Například zde:
```js run
-function sum(a, b) {
+function součet(a, b) {
return a + b;
}
-alert( sum(1, 2, 3, 4, 5) );
+alert( součet(1, 2, 3, 4, 5) );
```
-There will be no error because of "excessive" arguments. But of course in the result only the first two will be counted, so the result in the code above is `3`.
+Kvůli „přebytečným“ argumentům nenastane chyba, ale do výsledku se samozřejmě budou počítat jen první dva, takže výsledek v uvedeném kódu je `3`.
-The rest of the parameters can be included in the function definition by using three dots `...` followed by the name of the array that will contain them. The dots literally mean "gather the remaining parameters into an array".
+Zbylé parametry můžeme zahrnout do definice funkce pomocí tří teček `...`, za nimiž následuje název pole, které je bude obsahovat. Tečky doslova znamenají „shromáždi zbývající parametry do pole“.
-For instance, to gather all arguments into array `args`:
+Například abychom shromáždili všechny argumenty do pole `argumenty`:
```js run
-function sumAll(...args) { // args is the name for the array
- let sum = 0;
+function sečtiVše(...argumenty) { // argumenty je název pole
+ let součet = 0;
- for (let arg of args) sum += arg;
+ for (let arg of argumenty) součet += arg;
- return sum;
+ return součet;
}
-alert( sumAll(1) ); // 1
-alert( sumAll(1, 2) ); // 3
-alert( sumAll(1, 2, 3) ); // 6
+alert( sečtiVše(1) ); // 1
+alert( sečtiVše(1, 2) ); // 3
+alert( sečtiVše(1, 2, 3) ); // 6
```
-We can choose to get the first parameters as variables, and gather only the rest.
+Můžeme se rozhodnout, že první parametry uložíme do proměnných a shromáždíme pouze ty ostatní.
-Here the first two arguments go into variables and the rest go into `titles` array:
+Zde budou první dva argumenty uloženy do proměnných a ostatní se uloží do pole `tituly`:
```js run
-function showName(firstName, lastName, ...titles) {
- alert( firstName + ' ' + lastName ); // Julius Caesar
-
- // the rest go into titles array
- // i.e. titles = ["Consul", "Imperator"]
- alert( titles[0] ); // Consul
- alert( titles[1] ); // Imperator
- alert( titles.length ); // 2
+function zobrazJméno(křestníJméno, příjmení, ...tituly) {
+ alert( křestníJméno + ' ' + příjmení ); // Julius Caesar
+
+ // ostatní přijdou do pole tituly
+ // tj. tituly = ["Konzul", "Imperátor"]
+ alert( tituly[0] ); // Konzul
+ alert( tituly[1] ); // Imperátor
+ alert( tituly.length ); // 2
}
-showName("Julius", "Caesar", "Consul", "Imperator");
+zobrazJméno("Julius", "Caesar", "Konzul", "Imperátor");
```
-````warn header="The rest parameters must be at the end"
-The rest parameters gather all remaining arguments, so the following does not make sense and causes an error:
+````warn header="Zbytkové parametry musejí být na konci"
+Pole zbytkových parametrů shromažďuje všechny zbývající argumenty, takže následující zápis nedává smysl a vyvolá chybu:
```js
-function f(arg1, ...rest, arg2) { // arg2 after ...rest ?!
- // error
+function f(arg1, ...zbytek, arg2) { // arg2 po ...zbytek ?!
+ // chyba
}
```
-The `...rest` must always be last.
+`...zbytek` musí být vždy poslední.
````
-## The "arguments" variable
+## Proměnná „arguments“
-There is also a special array-like object named `arguments` that contains all arguments by their index.
+Existuje také speciální objekt podobný poli nazvaný `arguments`, který obsahuje všechny argumenty uložené podle jejich indexu.
-For instance:
+Například:
```js run
-function showName() {
+function zobrazJméno() {
alert( arguments.length );
alert( arguments[0] );
alert( arguments[1] );
- // it's iterable
+ // je iterovatelný
// for(let arg of arguments) alert(arg);
}
-// shows: 2, Julius, Caesar
-showName("Julius", "Caesar");
+// zobrazí: 2, Julius, Caesar
+zobrazJméno("Julius", "Caesar");
-// shows: 1, Ilya, undefined (no second argument)
-showName("Ilya");
+// zobrazí: 1, Ilja, undefined (druhý argument není)
+zobrazJméno("Ilja");
```
-In old times, rest parameters did not exist in the language, and using `arguments` was the only way to get all arguments of the function. And it still works, we can find it in the old code.
+V dřívějších dobách zbytkové parametry v jazyce neexistovaly a jediný způsob, jak získat všechny argumenty funkce, bylo použití `arguments`. A to stále funguje, můžeme to nalézt ve starých kódech.
-But the downside is that although `arguments` is both array-like and iterable, it's not an array. It does not support array methods, so we can't call `arguments.map(...)` for example.
+Nevýhodou však je, že ačkoli objekt `arguments` je podobný poli a iterovatelný, není to pole. Nepodporuje metody polí, takže nemůžeme volat například `arguments.map(...)`.
-Also, it always contains all arguments. We can't capture them partially, like we did with rest parameters.
+Navíc obsahuje vždy všechny argumenty. Nemůžeme je zachytit jen částečně, jak to můžeme udělat u zbytkových parametrů.
-So when we need these features, then rest parameters are preferred.
+Když tedy tuto vlastnost potřebujeme, dáváme přednost zbytkovým parametrům.
-````smart header="Arrow functions do not have `\"arguments\"`"
-If we access the `arguments` object from an arrow function, it takes them from the outer "normal" function.
+````smart header="Šipkové funkce nemají `„arguments“`"
+Jestliže přistoupíme k objektu `arguments` v šipkové funkci, převezme se z vnější „normální“ funkce.
-Here's an example:
+Příklad:
```js run
function f() {
- let showArg = () => alert(arguments[0]);
- showArg();
+ let zobrazArgumenty = () => alert(arguments[0]);
+ zobrazArgumenty();
}
f(1); // 1
```
-As we remember, arrow functions don't have their own `this`. Now we know they don't have the special `arguments` object either.
+Jak si pamatujeme, šipkové funkce nemají vlastní `this`. Nyní víme, že nemají ani speciální objekt `arguments`.
````
-## Spread syntax [#spread-syntax]
+## Roztažená syntaxe [#spread-syntax]
-We've just seen how to get an array from the list of parameters.
+Právě jsme viděli, jak vytvořit pole ze seznamu parametrů.
-But sometimes we need to do exactly the reverse.
+Někdy však potřebujeme udělat pravý opak.
-For instance, there's a built-in function [Math.max](mdn:js/Math/max) that returns the greatest number from a list:
+Například existuje vestavěná funkce [Math.max](mdn:js/Math/max), která vrací největší číslo ze seznamu:
```js run
alert( Math.max(3, 5, 1) ); // 5
```
-Now let's say we have an array `[3, 5, 1]`. How do we call `Math.max` with it?
+Nyní řekněme, že máme pole `[3, 5, 1]`. Jak na ně zavoláme `Math.max`?
-Passing it "as is" won't work, because `Math.max` expects a list of numeric arguments, not a single array:
+Předat pole „tak, jak je“ nebude fungovat, protože `Math.max` očekává seznam číselných argumentů, ne jediné pole:
```js run
-let arr = [3, 5, 1];
+let pole = [3, 5, 1];
*!*
-alert( Math.max(arr) ); // NaN
+alert( Math.max(pole) ); // NaN
*/!*
```
-And surely we can't manually list items in the code `Math.max(arr[0], arr[1], arr[2])`, because we may be unsure how many there are. As our script executes, there could be a lot, or there could be none. And that would get ugly.
+A samozřejmě nemůžeme v kódu ručně vyjmenovat prvky pole `Math.max(pole[0], pole[1], pole[2])`, protože nevíme jistě, kolik jich tam bude. Když se náš skript spustí, může jich tam být mnoho a nemusí tam být žádný. A to by mohlo špatně dopadnout.
-*Spread syntax* to the rescue! It looks similar to rest parameters, also using `...`, but does quite the opposite.
+Zachrání nás *roztažená (spread) syntaxe*! Podobá se zbytkovým parametrům v tom, že také používá `...`, ale činí to přesně naopak.
-When `...arr` is used in the function call, it "expands" an iterable object `arr` into the list of arguments.
+Když ve volání funkce použijeme `...pole`, iterovatelný objekt `pole` se „roztáhne“ do seznamu argumentů.
-For `Math.max`:
+Pro `Math.max`:
```js run
-let arr = [3, 5, 1];
+let pole = [3, 5, 1];
-alert( Math.max(...arr) ); // 5 (spread turns array into a list of arguments)
+alert( Math.max(...pole) ); // 5 (roztažení přetvoří pole na seznam argumentů)
```
-We also can pass multiple iterables this way:
+Tímto způsobem můžeme předat i více iterovatelných objektů:
```js run
-let arr1 = [1, -2, 3, 4];
-let arr2 = [8, 3, -8, 1];
+let pole1 = [1, -2, 3, 4];
+let pole2 = [8, 3, -8, 1];
-alert( Math.max(...arr1, ...arr2) ); // 8
+alert( Math.max(...pole1, ...pole2) ); // 8
```
-We can even combine the spread syntax with normal values:
+Můžeme dokonce kombinovat roztaženou syntaxi s běžnými hodnotami:
```js run
-let arr1 = [1, -2, 3, 4];
-let arr2 = [8, 3, -8, 1];
+let pole1 = [1, -2, 3, 4];
+let pole2 = [8, 3, -8, 1];
-alert( Math.max(1, ...arr1, 2, ...arr2, 25) ); // 25
+alert( Math.max(1, ...pole1, 2, ...pole2, 25) ); // 25
```
-Also, the spread syntax can be used to merge arrays:
+Roztaženou syntaxi můžeme použít i ke spojení polí:
```js run
-let arr = [3, 5, 1];
-let arr2 = [8, 9, 15];
+let pole = [3, 5, 1];
+let pole2 = [8, 9, 15];
*!*
-let merged = [0, ...arr, 2, ...arr2];
+let spojené = [0, ...pole, 2, ...pole2];
*/!*
-alert(merged); // 0,3,5,1,2,8,9,15 (0, then arr, then 2, then arr2)
+alert(spojené); // 0,3,5,1,2,8,9,15 (0, pak pole, pak 2, pak pole2)
```
-In the examples above we used an array to demonstrate the spread syntax, but any iterable will do.
+Ve výše uvedených příkladech jsme při předvádění roztažené syntaxe použili pole, ale funguje to na jakémkoli iterovatelném objektu.
-For instance, here we use the spread syntax to turn the string into array of characters:
+Například zde použijeme roztaženou syntaxi k převedení řetězce na pole znaků:
```js run
-let str = "Hello";
+let řetězec = "Ahoj";
-alert( [...str] ); // H,e,l,l,o
+alert( [...řetězec] ); // A,h,o,j
```
-The spread syntax internally uses iterators to gather elements, the same way as `for..of` does.
+Roztažená syntaxe vnitřně využívá iterátory ke shromažďování prvků stejným způsobem, jako cyklus `for..of`.
-So, for a string, `for..of` returns characters and `...str` becomes `"H","e","l","l","o"`. The list of characters is passed to array initializer `[...str]`.
+Pro řetězec tedy `for..of` vrátí znaky a `...řetězec` se převede na `"A","h","o","j"`. Seznam znaků se předá do inicializátoru pole `[...řetězec]`.
-For this particular task we could also use `Array.from`, because it converts an iterable (like a string) into an array:
+Pro tento konkrétní úkol bychom mohli použít i `Array.from`, protože tato metoda převádí iterovatelný objekt (např. řetězec) na pole:
```js run
-let str = "Hello";
+let řetězec = "Ahoj";
-// Array.from converts an iterable into an array
-alert( Array.from(str) ); // H,e,l,l,o
+// Array.from převede iterovatelný objekt na pole
+alert( Array.from(řetězec) ); // A,h,o,j
```
-The result is the same as `[...str]`.
+Výsledek je stejný jako u `[...řetězec]`.
-But there's a subtle difference between `Array.from(obj)` and `[...obj]`:
+Existuje však drobný rozdíl mezi `Array.from(obj)` a `[...obj]`:
-- `Array.from` operates on both array-likes and iterables.
-- The spread syntax works only with iterables.
+- `Array.from` funguje na objektech podobných poli i na iterovatelných objektech.
+- Roztažená syntaxe funguje jen na iterovatelných objektech.
-So, for the task of turning something into an array, `Array.from` tends to be more universal.
+Pro účel převedení něčeho jiného na pole tedy `Array.from` bývá univerzálnější.
+## Kopírování pole/objektu
-## Copy an array/object
+Pamatujete si, jak jsme [dříve](info:object-copy#cloning-and-merging-object-assign) hovořili o `Object.assign()`?
-Remember when we talked about `Object.assign()` [in the past](info:object-copy#cloning-and-merging-object-assign)?
-
-It is possible to do the same thing with the spread syntax.
+S roztaženou syntaxí můžeme udělat totéž.
```js run
-let arr = [1, 2, 3];
+let pole = [1, 2, 3];
*!*
-let arrCopy = [...arr]; // spread the array into a list of parameters
- // then put the result into a new array
+let kopiePole = [...pole]; // roztáhneme pole do seznamu parametrů
+ // pak uložíme výsledek do nového pole
*/!*
-// do the arrays have the same contents?
-alert(JSON.stringify(arr) === JSON.stringify(arrCopy)); // true
+// mají tato pole stejný obsah?
+alert(JSON.stringify(pole) === JSON.stringify(kopiePole)); // true
-// are the arrays equal?
-alert(arr === arrCopy); // false (not same reference)
+// jsou si tato pole rovna?
+alert(pole === kopiePole); // false (není to stejný odkaz)
-// modifying our initial array does not modify the copy:
-arr.push(4);
-alert(arr); // 1, 2, 3, 4
-alert(arrCopy); // 1, 2, 3
+// modifikace našeho původního pole nezmění kopii:
+pole.push(4);
+alert(pole); // 1, 2, 3, 4
+alert(kopiePole); // 1, 2, 3
```
-Note that it is possible to do the same thing to make a copy of an object:
+Všimněte si, že můžeme udělat totéž, abychom vytvořili kopii objektu:
```js run
-let obj = { a: 1, b: 2, c: 3 };
+let objekt = { a: 1, b: 2, c: 3 };
*!*
-let objCopy = { ...obj }; // spread the object into a list of parameters
- // then return the result in a new object
+let kopieObjektu = { ...objekt }; // roztáhneme objekt do seznamu parametrů
+ // pak vrátíme výsledek v novém objektu
*/!*
-// do the objects have the same contents?
-alert(JSON.stringify(obj) === JSON.stringify(objCopy)); // true
+// mají tyto objekty stejný obsah?
+alert(JSON.stringify(objekt) === JSON.stringify(kopieObjektu)); // true
-// are the objects equal?
-alert(obj === objCopy); // false (not same reference)
+// jsou si tyto objekty rovny?
+alert(objekt === kopieObjektu); // false (není to stejný odkaz)
-// modifying our initial object does not modify the copy:
-obj.d = 4;
-alert(JSON.stringify(obj)); // {"a":1,"b":2,"c":3,"d":4}
-alert(JSON.stringify(objCopy)); // {"a":1,"b":2,"c":3}
+// modifikace našeho původního objektu nezmění kopii:
+objekt.d = 4;
+alert(JSON.stringify(objekt)); // {"a":1,"b":2,"c":3,"d":4}
+alert(JSON.stringify(kopieObjektu)); // {"a":1,"b":2,"c":3}
```
-This way of copying an object is much shorter than `let objCopy = Object.assign({}, obj)` or for an array `let arrCopy = Object.assign([], arr)` so we prefer to use it whenever we can.
+Tento způsob kopírování objektu je mnohem kratší než `let kopieObjektu = Object.assign({}, objekt)` nebo pro pole `let kopiePole = Object.assign([], pole)`, takže mu dáváme přednost, kde jen můžeme.
-## Summary
+## Shrnutí
-When we see `"..."` in the code, it is either rest parameters or the spread syntax.
+Když v kódu vidíme `"..."`, jsou to buď zbytkové parametry, nebo roztažená syntaxe.
-There's an easy way to distinguish between them:
+Je možné mezi nimi snadno rozlišovat:
-- When `...` is at the end of function parameters, it's "rest parameters" and gathers the rest of the list of arguments into an array.
-- When `...` occurs in a function call or alike, it's called a "spread syntax" and expands an array into a list.
+- Když je `...` na konci funkčních parametrů, jsou to „zbytkové parametry“ a shromažďují zbytek seznamu argumentů do pole.
+- Když se `...` vyskytuje ve volání funkce nebo něčem podobném, nazývá se „roztažená syntaxe“ a roztáhne pole do seznamu.
-Use patterns:
+Vzory použití:
-- Rest parameters are used to create functions that accept any number of arguments.
-- The spread syntax is used to pass an array to functions that normally require a list of many arguments.
+- Zbytkové parametry se používají k vytváření funkcí, které přijímají libovolný počet argumentů.
+- Roztažená syntaxe se používá k předání pole do funkcí, které normálně vyžadují seznam mnoha argumentů.
-Together they help to travel between a list and an array of parameters with ease.
+Společně nám pomáhají snadno přepínat mezi seznamem a polem parametrů.
-All arguments of a function call are also available in "old-style" `arguments`: array-like iterable object.
+Všechny argumenty volání funkce jsou rovněž k dispozici „ve starém stylu“ v objektu `arguments`: iterovatelném objektu podobném poli.
diff --git a/1-js/06-advanced-functions/03-closure/1-closure-latest-changes/solution.md b/1-js/06-advanced-functions/03-closure/1-closure-latest-changes/solution.md
index 7cbd85ab7..18b1dc315 100644
--- a/1-js/06-advanced-functions/03-closure/1-closure-latest-changes/solution.md
+++ b/1-js/06-advanced-functions/03-closure/1-closure-latest-changes/solution.md
@@ -1,5 +1,5 @@
-The answer is: **Pete**.
+Odpověď zní: **Petr**.
-A function gets outer variables as they are now, it uses the most recent values.
+Funkce načítá vnější proměnné tak, jak vypadají právě v tuto chvíli. Používá poslední hodnoty.
-Old variable values are not saved anywhere. When a function wants a variable, it takes the current value from its own Lexical Environment or the outer one.
+Staré hodnoty proměnných se nikam neukládají. Když funkce chce proměnnou, vezme její aktuální hodnotu ze svého vlastního lexikálního prostředí nebo z vnějšího.
diff --git a/1-js/06-advanced-functions/03-closure/1-closure-latest-changes/task.md b/1-js/06-advanced-functions/03-closure/1-closure-latest-changes/task.md
index 819189773..924b3fd52 100644
--- a/1-js/06-advanced-functions/03-closure/1-closure-latest-changes/task.md
+++ b/1-js/06-advanced-functions/03-closure/1-closure-latest-changes/task.md
@@ -2,22 +2,22 @@ importance: 5
---
-# Does a function pickup latest changes?
+# Odrážejí se ve funkci poslední změny?
-The function sayHi uses an external variable name. When the function runs, which value is it going to use?
+Funkce `řekniAhoj` využívá název externí proměnné. Když bude spuštěna, kterou hodnotu použije?
```js
-let name = "John";
+let jméno = "Jan";
-function sayHi() {
- alert("Hi, " + name);
+function řekniAhoj() {
+ alert("Ahoj, " + jméno);
}
-name = "Pete";
+jméno = "Petr";
-sayHi(); // what will it show: "John" or "Pete"?
+řekniAhoj(); // co zobrazí: "Jan" nebo "Petr"?
```
-Such situations are common both in browser and server-side development. A function may be scheduled to execute later than it is created, for instance after a user action or a network request.
+Takové situace jsou běžné při vývoji v prohlížeči i na straně serveru. Funkce může být navržena ke spuštění později, než byla vytvořena, například po uživatelské akci nebo síťovém požadavku.
-So, the question is: does it pick up the latest changes?
+Otázka tedy zní: odráží poslední změny?
diff --git a/1-js/06-advanced-functions/03-closure/10-make-army/_js.view/solution.js b/1-js/06-advanced-functions/03-closure/10-make-army/_js.view/solution.js
index a26578ae1..ca8e82a08 100644
--- a/1-js/06-advanced-functions/03-closure/10-make-army/_js.view/solution.js
+++ b/1-js/06-advanced-functions/03-closure/10-make-army/_js.view/solution.js
@@ -1,13 +1,13 @@
-function makeArmy() {
+function vytvořArmádu() {
- let shooters = [];
+ let střelci = [];
for(let i = 0; i < 10; i++) {
- let shooter = function() { // shooter function
- alert( i ); // should show its number
+ let střelec = function() { // funkce střelec
+ alert( i ); // by měla zobrazit své číslo
};
- shooters.push(shooter);
+ střelci.push(střelec);
}
- return shooters;
+ return střelci;
}
diff --git a/1-js/06-advanced-functions/03-closure/10-make-army/_js.view/source.js b/1-js/06-advanced-functions/03-closure/10-make-army/_js.view/source.js
index 7c7aaa1e3..e908b1f0b 100644
--- a/1-js/06-advanced-functions/03-closure/10-make-army/_js.view/source.js
+++ b/1-js/06-advanced-functions/03-closure/10-make-army/_js.view/source.js
@@ -1,22 +1,22 @@
-function makeArmy() {
- let shooters = [];
+function vytvořArmádu() {
+ let střelci = [];
let i = 0;
while (i < 10) {
- let shooter = function() { // shooter function
- alert( i ); // should show its number
+ let střelec = function() { // funkce střelec
+ alert( i ); // by měla zobrazit své číslo
};
- shooters.push(shooter);
+ střelci.push(střelec);
i++;
}
- return shooters;
+ return střelci;
}
/*
-let army = makeArmy();
+let armáda = vytvořArmádu();
-army[0](); // the shooter number 0 shows 10
-army[5](); // and number 5 also outputs 10...
-// ... all shooters show 10 instead of their 0, 1, 2, 3...
+armáda[0](); // střelec číslo 0 zobrazí 10
+armáda[5](); // a číslo 5 zobrazí také 10...
+// ... všichni střelci zobrazí 10 místo svého čísla 0, 1, 2, 3...
*/
diff --git a/1-js/06-advanced-functions/03-closure/10-make-army/_js.view/test.js b/1-js/06-advanced-functions/03-closure/10-make-army/_js.view/test.js
index b61e6e4db..f8c2c866c 100644
--- a/1-js/06-advanced-functions/03-closure/10-make-army/_js.view/test.js
+++ b/1-js/06-advanced-functions/03-closure/10-make-army/_js.view/test.js
@@ -1,20 +1,20 @@
-describe("army", function() {
+describe("armáda", function() {
- let army;
+ let armáda;
before(function() {
- army = makeArmy();
+ armáda = vytvořArmádu();
window.alert = sinon.stub(window, "alert");
});
- it("army[0] shows 0", function() {
- army[0]();
+ it("armáda[0] zobrazí 0", function() {
+ armáda[0]();
assert(alert.calledWith(0));
});
- it("army[5] shows 5", function() {
- army[5]();
+ it("armáda[5] zobrazí 5", function() {
+ armáda[5]();
assert(alert.calledWith(5));
});
diff --git a/1-js/06-advanced-functions/03-closure/10-make-army/solution.md b/1-js/06-advanced-functions/03-closure/10-make-army/solution.md
index 9d99aa717..fd6af39ff 100644
--- a/1-js/06-advanced-functions/03-closure/10-make-army/solution.md
+++ b/1-js/06-advanced-functions/03-closure/10-make-army/solution.md
@@ -1,17 +1,17 @@
-Let's examine what exactly happens inside `makeArmy`, and the solution will become obvious.
+Prozkoumejme, co přesně se děje uvnitř funkce `vytvořArmádu`, a řešení bude zřejmé.
-1. It creates an empty array `shooters`:
+1. Vytvoří se prázdné pole `střelci`:
```js
- let shooters = [];
+ let střelci = [];
```
-2. Fills it with functions via `shooters.push(function)` in the loop.
+2. V cyklu se naplní funkcemi pomocí `střelci.push(function)`.
- Every element is a function, so the resulting array looks like this:
+ Každý prvek je funkce, takže výsledné pole vypadá takto:
```js no-beautify
- shooters = [
+ střelci = [
function () { alert(i); },
function () { alert(i); },
function () { alert(i); },
@@ -25,105 +25,104 @@ Let's examine what exactly happens inside `makeArmy`, and the solution will beco
];
```
-3. The array is returned from the function.
+3. Toto pole funkce vrátí.
- Then, later, the call to any member, e.g. `army[5]()` will get the element `army[5]` from the array (which is a function) and calls it.
+ Pak později volání kteréhokoli jeho prvku, např. `armáda[5]()`, načte z pole prvek `armáda[5]` (což je funkce) a zavolá jej.
- Now why do all such functions show the same value, `10`?
+ Proč nyní všechny tyto funkce zobrazí stejnou hodnotu, `10`?
- That's because there's no local variable `i` inside `shooter` functions. When such a function is called, it takes `i` from its outer lexical environment.
+ Je to proto, že uvnitř funkcí `střelec` neexistuje žádná lokální proměnná `i`. Když je taková funkce volána, převezme `i` z vnějšího lexikálního prostředí.
- Then, what will be the value of `i`?
+ Jaká pak bude hodnota proměnné `i`?
- If we look at the source:
+ Když se podíváme na zdrojový kód:
```js
- function makeArmy() {
+ function vytvořArmádu() {
...
let i = 0;
while (i < 10) {
- let shooter = function() { // shooter function
- alert( i ); // should show its number
+ let střelec = function() { // funkce střelec
+ alert( i ); // by měla zobrazit své číslo
};
- shooters.push(shooter); // add function to the array
+ střelci.push(střelec); // přidá funkci do pole
i++;
}
...
}
```
- We can see that all `shooter` functions are created in the lexical environment of `makeArmy()` function. But when `army[5]()` is called, `makeArmy` has already finished its job, and the final value of `i` is `10` (`while` stops at `i=10`).
+ Vidíme, že všechny funkce `střelec` jsou vytvořeny v lexikálním prostředí funkce `vytvořArmádu()`. Když je však volána `armáda[5]()`, funkce `vytvořArmádu` již ukončila svou práci a poslední hodnota `i` je `10` (`while` se zastaví na `i=10`).
- As the result, all `shooter` functions get the same value from the outer lexical environment and that is, the last value, `i=10`.
+ Výsledkem je, že všechny funkce `střelec` převezmou z vnějšího lexikálního prostředí stejnou hodnotu a tou bude poslední hodnota, `i=10`.

- As you can see above, on each iteration of a `while {...}` block, a new lexical environment is created. So, to fix this, we can copy the value of `i` into a variable within the `while {...}` block, like this:
+ Jak vidíte výše, při každé iteraci bloku `while {...}` bude vytvořeno nové lexikální prostředí. Abychom to opravili, můžeme zkopírovat hodnotu `i` do proměnné uvnitř bloku `while {...}` třeba takto:
```js run
- function makeArmy() {
- let shooters = [];
+ function vytvořArmádu() {
+ let střelci = [];
let i = 0;
while (i < 10) {
*!*
let j = i;
*/!*
- let shooter = function() { // shooter function
- alert( *!*j*/!* ); // should show its number
+ let střelec = function() { // funkce střelec
+ alert( *!*j*/!* ); // by měla zobrazit své číslo
};
- shooters.push(shooter);
+ střelci.push(střelec);
i++;
}
- return shooters;
+ return střelci;
}
- let army = makeArmy();
+ let armáda = vytvořArmádu();
- // Now the code works correctly
- army[0](); // 0
- army[5](); // 5
+ // Nyní kód funguje správně
+ armáda[0](); // 0
+ armáda[5](); // 5
```
- Here `let j = i` declares an "iteration-local" variable `j` and copies `i` into it. Primitives are copied "by value", so we actually get an independent copy of `i`, belonging to the current loop iteration.
+ Zde `let j = i` deklaruje „iteračně lokální“ proměnnou `j` a zkopíruje do ní `i`. Primitivy se kopírují „hodnotou“, takže ve skutečnosti získáme nezávislou kopii `i`, která patří do aktuální iterace cyklu.
- The shooters work correctly, because the value of `i` now lives a little bit closer. Not in `makeArmy()` Lexical Environment, but in the Lexical Environment that corresponds to the current loop iteration:
+ Střelci budou fungovat správně, protože hodnota `i` nyní existuje trochu blíže. Není v lexikálním prostředí funkce `vytvořArmádu()`, ale v lexikálním prostředí, které odpovídá aktuální iteraci cyklu:

- Such a problem could also be avoided if we used `for` in the beginning, like this:
+ Tomuto problému se lze vyhnout i tak, že na začátku použijeme `for`, třeba takto:
```js run demo
- function makeArmy() {
+ function vytvořArmádu() {
- let shooters = [];
+ let střelci = [];
*!*
for(let i = 0; i < 10; i++) {
*/!*
- let shooter = function() { // shooter function
- alert( i ); // should show its number
+ let střelec = function() { // funkce střelec
+ alert( i ); // by měla zobrazit své číslo
};
- shooters.push(shooter);
+ střelci.push(střelec);
}
- return shooters;
+ return střelci;
}
- let army = makeArmy();
+ let armáda = vytvořArmádu();
- army[0](); // 0
- army[5](); // 5
+ armáda[0](); // 0
+ armáda[5](); // 5
```
- That's essentially the same, because `for` on each iteration generates a new lexical environment, with its own variable `i`. So `shooter` generated in every iteration references its own `i`, from that very iteration.
+ To je v zásadě totéž, protože `for` při každé své iteraci vygeneruje nové lexikální prostředí se svou vlastní proměnnou `i`. Takže `střelec` generovaný v každé iteraci odkazuje na své vlastní `i` přímo z této iterace.

-Now, as you've put so much effort into reading this, and the final recipe is so simple - just use `for`, you may wonder -- was it worth that?
+Když jste vložili tolik námahy do přečtení tohoto řešení a konečný recept je tak jednoduchý -- prostě použijeme `for`, můžete se divit -- mělo to cenu?
-Well, if you could easily answer the question, you wouldn't read the solution. So, hopefully this task must have helped you to understand things a bit better.
-
-Besides, there are indeed cases when one prefers `while` to `for`, and other scenarios, where such problems are real.
+Inu, kdybyste na tuto otázku dokázali snadno odpovědět, nečetli byste řešení. Snad vám tedy tato úloha pomohla trochu lépe všemu porozumět.
+Kromě toho zajisté existují případy, kdy člověk dává přednost `while` před `for`, i jiné scénáře, v nichž takové problémy opravdu nastanou.
diff --git a/1-js/06-advanced-functions/03-closure/10-make-army/task.md b/1-js/06-advanced-functions/03-closure/10-make-army/task.md
index f50c7dc20..27f69e70c 100644
--- a/1-js/06-advanced-functions/03-closure/10-make-army/task.md
+++ b/1-js/06-advanced-functions/03-closure/10-make-army/task.md
@@ -2,40 +2,39 @@ importance: 5
---
-# Army of functions
+# Armáda funkcí
-The following code creates an array of `shooters`.
+Následující kód vytvoří pole `střelci`.
-Every function is meant to output its number. But something is wrong...
+Každá funkce má vypsat své číslo. Ale něco je špatně...
```js run
-function makeArmy() {
- let shooters = [];
+function vytvořArmádu() {
+ let střelci = [];
let i = 0;
while (i < 10) {
- let shooter = function() { // create a shooter function,
- alert( i ); // that should show its number
+ let střelec = function() { // vytvoříme funkci střelec,
+ alert( i ); // která by měla zobrazit své číslo
};
- shooters.push(shooter); // and add it to the array
+ střelci.push(střelec); // a přidáme ji do pole
i++;
}
- // ...and return the array of shooters
- return shooters;
+ // ...a vrátíme pole střelci
+ return střelci;
}
-let army = makeArmy();
+let armáda = vytvořArmádu();
*!*
-// all shooters show 10 instead of their numbers 0, 1, 2, 3...
-army[0](); // 10 from the shooter number 0
-army[1](); // 10 from the shooter number 1
-army[2](); // 10 ...and so on.
+// všichni střelci zobrazí 10 místo svých čísel 0, 1, 2, 3...
+armáda[0](); // 10 od střelce číslo 0
+armáda[1](); // 10 od střelce číslo 1
+armáda[2](); // 10 ...a tak dále.
*/!*
```
-Why do all of the shooters show the same value?
-
-Fix the code so that they work as intended.
+Proč všichni střelci zobrazují stejnou hodnotu?
+Opravte kód, aby fungoval tak, jak je zamýšleno.
diff --git a/1-js/06-advanced-functions/03-closure/2-closure-variable-access/solution.md b/1-js/06-advanced-functions/03-closure/2-closure-variable-access/solution.md
index 0a522132f..6ad8df764 100644
--- a/1-js/06-advanced-functions/03-closure/2-closure-variable-access/solution.md
+++ b/1-js/06-advanced-functions/03-closure/2-closure-variable-access/solution.md
@@ -1,9 +1,9 @@
-The answer is: **Pete**.
+Odpověď zní: **Petr**.
-The `work()` function in the code below gets `name` from the place of its origin through the outer lexical environment reference:
+Funkce `pracuj()` uvedená v následujícím kódu načte `jméno` z místa svého vzniku odkazem na vnější lexikální prostředí:

-So, the result is `"Pete"` here.
+Výsledkem zde je tedy `"Petr"`.
-But if there were no `let name` in `makeWorker()`, then the search would go outside and take the global variable as we can see from the chain above. In that case the result would be `"John"`.
+Kdyby však ve funkci `vytvořPracovníka()` nebylo `let jméno`, pak by hledání pokračovalo dál ven a převzalo globální proměnnou, jak vidíme v uvedeném řetězci. V tom případě by výsledek byl `"Jan"`.
diff --git a/1-js/06-advanced-functions/03-closure/2-closure-variable-access/task.md b/1-js/06-advanced-functions/03-closure/2-closure-variable-access/task.md
index d12a385c8..bba9be2b1 100644
--- a/1-js/06-advanced-functions/03-closure/2-closure-variable-access/task.md
+++ b/1-js/06-advanced-functions/03-closure/2-closure-variable-access/task.md
@@ -2,28 +2,28 @@ importance: 5
---
-# Which variables are available?
+# Které proměnné jsou dostupné?
-The function `makeWorker` below makes another function and returns it. That new function can be called from somewhere else.
+Následující funkce `vytvořPracovníka` vytvoří jinou funkci a vrátí ji. Nová funkce může být volána odjinud.
-Will it have access to the outer variables from its creation place, or the invocation place, or both?
+Bude mít přístup k vnějším proměnným z místa svého vzniku, nebo z místa volání, nebo z obojího?
```js
-function makeWorker() {
- let name = "Pete";
+function vytvořPracovníka() {
+ let jméno = "Petr";
return function() {
- alert(name);
+ alert(jméno);
};
}
-let name = "John";
+let jméno = "Jan";
-// create a function
-let work = makeWorker();
+// vytvoření funkce
+let pracuj = vytvořPracovníka();
-// call it
-work(); // what will it show?
+// její volání
+pracuj(); // co zobrazí?
```
-Which value it will show? "Pete" or "John"?
+Kterou hodnotu zobrazí? „Petr“ nebo „Jan“?
diff --git a/1-js/06-advanced-functions/03-closure/3-counter-independent/solution.md b/1-js/06-advanced-functions/03-closure/3-counter-independent/solution.md
index 25ecbea4c..b7fc9d64a 100644
--- a/1-js/06-advanced-functions/03-closure/3-counter-independent/solution.md
+++ b/1-js/06-advanced-functions/03-closure/3-counter-independent/solution.md
@@ -1,5 +1,5 @@
-The answer: **0,1.**
+Odpověď: **0,1.**
-Functions `counter` and `counter2` are created by different invocations of `makeCounter`.
+Funkce `čítač` a `čítač2` byly vytvořeny různými voláními funkce `vytvořČítač`.
-So they have independent outer Lexical Environments, each one has its own `count`.
+Mají tedy nezávislá vnější lexikální prostředí, každé z nich má svůj vlastní `počet`.
diff --git a/1-js/06-advanced-functions/03-closure/3-counter-independent/task.md b/1-js/06-advanced-functions/03-closure/3-counter-independent/task.md
index e8c17dd31..f6bb4b42e 100644
--- a/1-js/06-advanced-functions/03-closure/3-counter-independent/task.md
+++ b/1-js/06-advanced-functions/03-closure/3-counter-independent/task.md
@@ -2,30 +2,30 @@ importance: 5
---
-# Are counters independent?
+# Jsou čítače nezávislé?
-Here we make two counters: `counter` and `counter2` using the same `makeCounter` function.
+Zde vytvoříme dva čítače: `čítač` a `čítač2` pomocí téže funkce `vytvořČítač`.
-Are they independent? What is the second counter going to show? `0,1` or `2,3` or something else?
+Jsou nezávislé? Co zobrazí druhý čítač? `0,1` nebo `2,3` nebo něco jiného?
```js
-function makeCounter() {
- let count = 0;
+function vytvořČítač() {
+ let počet = 0;
return function() {
- return count++;
+ return počet++;
};
}
-let counter = makeCounter();
-let counter2 = makeCounter();
+let čítač = vytvořČítač();
+let čítač2 = vytvořČítač();
-alert( counter() ); // 0
-alert( counter() ); // 1
+alert( čítač() ); // 0
+alert( čítač() ); // 1
*!*
-alert( counter2() ); // ?
-alert( counter2() ); // ?
+alert( čítač2() ); // ?
+alert( čítač2() ); // ?
*/!*
```
diff --git a/1-js/06-advanced-functions/03-closure/4-counter-object-independent/solution.md b/1-js/06-advanced-functions/03-closure/4-counter-object-independent/solution.md
index cd4e641e4..9ece7f811 100644
--- a/1-js/06-advanced-functions/03-closure/4-counter-object-independent/solution.md
+++ b/1-js/06-advanced-functions/03-closure/4-counter-object-independent/solution.md
@@ -1,24 +1,22 @@
+Jistě že to bude fungovat správně.
-Surely it will work just fine.
-
-Both nested functions are created within the same outer Lexical Environment, so they share access to the same `count` variable:
+Obě vnořené funkce jsou vytvořeny uvnitř stejného vnějšího lexikálního prostředí, takže mají společný přístup ke stejné proměnné `počet`:
```js run
-function Counter() {
- let count = 0;
+function Čítač() {
+ let počet = 0;
- this.up = function() {
- return ++count;
+ this.zvyš = function() {
+ return ++počet;
};
-
- this.down = function() {
- return --count;
+ this.sniž = function() {
+ return --počet;
};
}
-let counter = new Counter();
+let čítač = new Čítač();
-alert( counter.up() ); // 1
-alert( counter.up() ); // 2
-alert( counter.down() ); // 1
+alert( čítač.zvyš() ); // 1
+alert( čítač.zvyš() ); // 2
+alert( čítač.sniž() ); // 1
```
diff --git a/1-js/06-advanced-functions/03-closure/4-counter-object-independent/task.md b/1-js/06-advanced-functions/03-closure/4-counter-object-independent/task.md
index d770b0ffc..785d64ba6 100644
--- a/1-js/06-advanced-functions/03-closure/4-counter-object-independent/task.md
+++ b/1-js/06-advanced-functions/03-closure/4-counter-object-independent/task.md
@@ -2,28 +2,28 @@ importance: 5
---
-# Counter object
+# Objekt čítače
-Here a counter object is made with the help of the constructor function.
+Zde je vytvořen objekt čítače pomocí konstruktoru.
-Will it work? What will it show?
+Bude to fungovat? Co se zobrazí?
```js
-function Counter() {
- let count = 0;
+function Čítač() {
+ let počet = 0;
- this.up = function() {
- return ++count;
+ this.zvyš = function() {
+ return ++počet;
};
- this.down = function() {
- return --count;
+ this.sniž = function() {
+ return --počet;
};
}
-let counter = new Counter();
+let čítač = new Čítač();
-alert( counter.up() ); // ?
-alert( counter.up() ); // ?
-alert( counter.down() ); // ?
+alert( čítač.zvyš() ); // ?
+alert( čítač.zvyš() ); // ?
+alert( čítač.sniž() ); // ?
```
diff --git a/1-js/06-advanced-functions/03-closure/5-function-in-if/solution.md b/1-js/06-advanced-functions/03-closure/5-function-in-if/solution.md
index e2e7a91b3..ed26d4887 100644
--- a/1-js/06-advanced-functions/03-closure/5-function-in-if/solution.md
+++ b/1-js/06-advanced-functions/03-closure/5-function-in-if/solution.md
@@ -1,3 +1,3 @@
-The result is **an error**.
+Výsledkem bude **chyba**.
-The function `sayHi` is declared inside the `if`, so it only lives inside it. There is no `sayHi` outside.
\ No newline at end of file
+Funkce `řekniAhoj` je deklarována uvnitř `if`, takže bude existovat jen uvnitř něj. Vně žádné `řekniAhoj` není.
\ No newline at end of file
diff --git a/1-js/06-advanced-functions/03-closure/5-function-in-if/task.md b/1-js/06-advanced-functions/03-closure/5-function-in-if/task.md
index 4e386eec5..302f6037f 100644
--- a/1-js/06-advanced-functions/03-closure/5-function-in-if/task.md
+++ b/1-js/06-advanced-functions/03-closure/5-function-in-if/task.md
@@ -1,22 +1,22 @@
importance: 5
---
-# Function in if
+# Funkce v if
-Look at the code. What will be the result of the call at the last line?
+Podívejte se na kód. Jaký bude výsledek volání na posledním řádku?
```js run
-let phrase = "Hello";
+let věta = "Ahoj";
if (true) {
- let user = "John";
+ let uživatel = "Jan";
- function sayHi() {
- alert(`${phrase}, ${user}`);
+ function řekniAhoj() {
+ alert(`${věta}, ${uživatel}`);
}
}
*!*
-sayHi();
+řekniAhoj();
*/!*
```
diff --git a/1-js/06-advanced-functions/03-closure/6-closure-sum/solution.md b/1-js/06-advanced-functions/03-closure/6-closure-sum/solution.md
index a6679cd20..8c426d44d 100644
--- a/1-js/06-advanced-functions/03-closure/6-closure-sum/solution.md
+++ b/1-js/06-advanced-functions/03-closure/6-closure-sum/solution.md
@@ -1,17 +1,17 @@
-For the second parentheses to work, the first ones must return a function.
+Aby druhé závorky fungovaly, ty první musejí vrátit funkci.
-Like this:
+Například:
```js run
-function sum(a) {
+function sečti(a) {
return function(b) {
- return a + b; // takes "a" from the outer lexical environment
+ return a + b; // vezme "a" z vnějšího lexikálního prostředí
};
}
-alert( sum(1)(2) ); // 3
-alert( sum(5)(-1) ); // 4
+alert( sečti(1)(2) ); // 3
+alert( sečti(5)(-1) ); // 4
```
diff --git a/1-js/06-advanced-functions/03-closure/6-closure-sum/task.md b/1-js/06-advanced-functions/03-closure/6-closure-sum/task.md
index b45758562..5e0e66df1 100644
--- a/1-js/06-advanced-functions/03-closure/6-closure-sum/task.md
+++ b/1-js/06-advanced-functions/03-closure/6-closure-sum/task.md
@@ -2,16 +2,16 @@ importance: 4
---
-# Sum with closures
+# Součet s uzávěry
-Write function `sum` that works like this: `sum(a)(b) = a+b`.
+Napište funkci `sečti`, která bude fungovat takto: `sečti(a)(b) = a+b`.
-Yes, exactly this way, using double parentheses (not a mistype).
+Ano, přesně takto, pomocí dvojích závorek (to není překlep).
-For instance:
+Například:
```js
-sum(1)(2) = 3
-sum(5)(-1) = 4
+sečti(1)(2) = 3
+sečti(5)(-1) = 4
```
diff --git a/1-js/06-advanced-functions/03-closure/7-let-scope/solution.md b/1-js/06-advanced-functions/03-closure/7-let-scope/solution.md
index b16b35290..d24d73aa1 100644
--- a/1-js/06-advanced-functions/03-closure/7-let-scope/solution.md
+++ b/1-js/06-advanced-functions/03-closure/7-let-scope/solution.md
@@ -1,40 +1,40 @@
-The result is: **error**.
+Výsledek bude: **chyba**.
-Try running it:
+Zkuste si to spustit:
```js run
let x = 1;
-function func() {
+function funkce() {
*!*
- console.log(x); // ReferenceError: Cannot access 'x' before initialization
+ console.log(x); // ReferenceError: Nelze přistupovat k 'x' před inicializací
*/!*
let x = 2;
}
-func();
+funkce();
```
-In this example we can observe the peculiar difference between a "non-existing" and "uninitialized" variable.
+V tomto příkladu můžeme vidět pozoruhodný rozdíl mezi „neexistující“ a „neinicializovanou“ proměnnou.
-As you may have read in the article [](info:closure), a variable starts in the "uninitialized" state from the moment when the execution enters a code block (or a function). And it stays uninitalized until the corresponding `let` statement.
+Jak jste si mohli přečíst v článku [](info:closure), proměnná začíná v „neinicializovaném“ stavu ve chvíli, kdy běh vstoupí do kódového bloku (nebo do funkce). A zůstane neinicializovaná až do příslušného příkazu `let`.
-In other words, a variable technically exists, but can't be used before `let`.
+Jinými slovy, před `let` proměnná technicky existuje, ale nemůže být používána.
-The code above demonstrates it.
+Uvedený kód to demonstruje.
```js
-function func() {
+function funkce() {
*!*
- // the local variable x is known to the engine from the beginning of the function,
- // but "uninitialized" (unusable) until let ("dead zone")
- // hence the error
+ // motor zná lokální proměnnou x od začátku této funkce,
+ // ale ta je „neinicializovaná“ (nepoužitelná) až do příkazu let („mrtvá zóna“)
+ // proto chyba
*/!*
- console.log(x); // ReferenceError: Cannot access 'x' before initialization
+ console.log(x); // ReferenceError: Nelze přistupovat k 'x' před inicializací
let x = 2;
}
```
-This zone of temporary unusability of a variable (from the beginning of the code block till `let`) is sometimes called the "dead zone".
+Tato zóna dočasné nepoužitelnosti proměnné (od začátku kódového bloku do `let`) se někdy nazývá „mrtvá zóna“.
diff --git a/1-js/06-advanced-functions/03-closure/7-let-scope/task.md b/1-js/06-advanced-functions/03-closure/7-let-scope/task.md
index fb7445e66..07c5fd889 100644
--- a/1-js/06-advanced-functions/03-closure/7-let-scope/task.md
+++ b/1-js/06-advanced-functions/03-closure/7-let-scope/task.md
@@ -2,20 +2,20 @@ importance: 4
---
-# Is variable visible?
+# Je proměnná viditelná?
-What will be the result of this code?
+Jaký bude výsledek tohoto kódu?
```js
let x = 1;
-function func() {
+function funkce() {
console.log(x); // ?
let x = 2;
}
-func();
+funkce();
```
-P.S. There's a pitfall in this task. The solution is not obvious.
+P.S. V tomto úkolu je chyták. Řešení není očividné.
diff --git a/1-js/06-advanced-functions/03-closure/8-filter-through-function/_js.view/solution.js b/1-js/06-advanced-functions/03-closure/8-filter-through-function/_js.view/solution.js
index 66a149d98..fc3e21b87 100644
--- a/1-js/06-advanced-functions/03-closure/8-filter-through-function/_js.view/solution.js
+++ b/1-js/06-advanced-functions/03-closure/8-filter-through-function/_js.view/solution.js
@@ -1,8 +1,8 @@
-function inArray(arr) {
- return x => arr.includes(x);
+function vPoli(pole) {
+ return x => pole.includes(x);
}
-function inBetween(a, b) {
+function mezi(a, b) {
return x => (x >= a && x <= b);
}
\ No newline at end of file
diff --git a/1-js/06-advanced-functions/03-closure/8-filter-through-function/_js.view/source.js b/1-js/06-advanced-functions/03-closure/8-filter-through-function/_js.view/source.js
index 74989df28..a6efd478b 100644
--- a/1-js/06-advanced-functions/03-closure/8-filter-through-function/_js.view/source.js
+++ b/1-js/06-advanced-functions/03-closure/8-filter-through-function/_js.view/source.js
@@ -1,10 +1,10 @@
-let arr = [1, 2, 3, 4, 5, 6, 7];
+let pole = [1, 2, 3, 4, 5, 6, 7];
-function inBetween(a, b) {
- // ...your code...
+function mezi(a, b) {
+ // ...váš kód...
}
-function inArray(arr) {
- // ...your code...
+function vPoli(pole) {
+ // ...váš kód...
}
diff --git a/1-js/06-advanced-functions/03-closure/8-filter-through-function/_js.view/test.js b/1-js/06-advanced-functions/03-closure/8-filter-through-function/_js.view/test.js
index 86d2d3b48..701dbe103 100644
--- a/1-js/06-advanced-functions/03-closure/8-filter-through-function/_js.view/test.js
+++ b/1-js/06-advanced-functions/03-closure/8-filter-through-function/_js.view/test.js
@@ -1,21 +1,21 @@
-describe("inArray", function() {
- let arr = [1, 2, 3, 4, 5, 6, 7];
+describe("vPoli", function() {
+ let pole = [1, 2, 3, 4, 5, 6, 7];
- it("returns the filter for values in array", function() {
+ it("vrátí filtr pro hodnoty v poli", function() {
- let filter = inArray(arr);
- assert.isTrue(filter(5));
- assert.isFalse(filter(0));
+ let filtr = vPoli(pole);
+ assert.isTrue(filtr(5));
+ assert.isFalse(filtr(0));
});
});
-describe("inBetween", function() {
+describe("mezi", function() {
- it("returns the filter for values between", function() {
- let filter = inBetween(3, 6);
- assert.isTrue(filter(5));
- assert.isFalse(filter(0));
+ it("vrátí filtr pro hodnoty mezi", function() {
+ let filtr = mezi(3, 6);
+ assert.isTrue(filtr(5));
+ assert.isFalse(filtr(0));
});
});
diff --git a/1-js/06-advanced-functions/03-closure/8-filter-through-function/solution.md b/1-js/06-advanced-functions/03-closure/8-filter-through-function/solution.md
index 46c5514a8..96b031c67 100644
--- a/1-js/06-advanced-functions/03-closure/8-filter-through-function/solution.md
+++ b/1-js/06-advanced-functions/03-closure/8-filter-through-function/solution.md
@@ -1,26 +1,26 @@
-# Filter inBetween
+# Filtr mezi
```js run
-function inBetween(a, b) {
+function mezi(a, b) {
return function(x) {
return x >= a && x <= b;
};
}
-let arr = [1, 2, 3, 4, 5, 6, 7];
-alert( arr.filter(inBetween(3, 6)) ); // 3,4,5,6
+let pole = [1, 2, 3, 4, 5, 6, 7];
+alert( pole.filter(mezi(3, 6)) ); // 3,4,5,6
```
-# Filter inArray
+# Filtr vPoli
```js run demo
-function inArray(arr) {
+function vPoli(pole) {
return function(x) {
- return arr.includes(x);
+ return pole.includes(x);
};
}
-let arr = [1, 2, 3, 4, 5, 6, 7];
-alert( arr.filter(inArray([1, 2, 10])) ); // 1,2
+let pole = [1, 2, 3, 4, 5, 6, 7];
+alert( pole.filter(vPoli([1, 2, 10])) ); // 1,2
```
diff --git a/1-js/06-advanced-functions/03-closure/8-filter-through-function/task.md b/1-js/06-advanced-functions/03-closure/8-filter-through-function/task.md
index d1c39f949..d88618381 100644
--- a/1-js/06-advanced-functions/03-closure/8-filter-through-function/task.md
+++ b/1-js/06-advanced-functions/03-closure/8-filter-through-function/task.md
@@ -2,28 +2,28 @@ importance: 5
---
-# Filter through function
+# Filtrace pomocí funkce
-We have a built-in method `arr.filter(f)` for arrays. It filters all elements through the function `f`. If it returns `true`, then that element is returned in the resulting array.
+Pro pole máme vestavěnou metodu `pole.filter(f)`, která filtruje všechny prvky pomocí funkce `f`. Jestliže `f` vrátí `true`, bude prvek vrácen ve výsledném poli.
-Make a set of "ready to use" filters:
+Vytvořte sadu filtrů „připravených k použití“:
-- `inBetween(a, b)` -- between `a` and `b` or equal to them (inclusively).
-- `inArray([...])` -- in the given array.
+- `mezi(a, b)` -- mezi `a` a `b` nebo rovno některému z nich (inkluzívně).
+- `vPoli([...])` -- v zadaném poli.
-The usage must be like this:
+Použití musí být následující:
-- `arr.filter(inBetween(3,6))` -- selects only values between 3 and 6.
-- `arr.filter(inArray([1,2,3]))` -- selects only elements matching with one of the members of `[1,2,3]`.
+- `pole.filter(mezi(3,6))` -- vybere jen hodnoty mezi 3 a 6.
+- `pole.filter(vPoli([1,2,3]))` -- vybere jen prvky, které se rovnají některému z prvků pole `[1,2,3]`.
-For instance:
+Například:
```js
-/* .. your code for inBetween and inArray */
-let arr = [1, 2, 3, 4, 5, 6, 7];
+/* .. váš kód funkcí mezi a vPoli */
+let pole = [1, 2, 3, 4, 5, 6, 7];
-alert( arr.filter(inBetween(3, 6)) ); // 3,4,5,6
+alert( pole.filter(mezi(3, 6)) ); // 3,4,5,6
-alert( arr.filter(inArray([1, 2, 10])) ); // 1,2
+alert( pole.filter(vPoli([1, 2, 10])) ); // 1,2
```
diff --git a/1-js/06-advanced-functions/03-closure/9-sort-by-field/_js.view/solution.js b/1-js/06-advanced-functions/03-closure/9-sort-by-field/_js.view/solution.js
index 8a71c869d..db749fdfd 100644
--- a/1-js/06-advanced-functions/03-closure/9-sort-by-field/_js.view/solution.js
+++ b/1-js/06-advanced-functions/03-closure/9-sort-by-field/_js.view/solution.js
@@ -1,3 +1,3 @@
-function byField(fieldName){
- return (a, b) => a[fieldName] > b[fieldName] ? 1 : -1;
+function podleVlastnosti(názevVlastnosti){
+ return (a, b) => a[názevVlastnosti] > b[názevVlastnosti] ? 1 : -1;
}
diff --git a/1-js/06-advanced-functions/03-closure/9-sort-by-field/_js.view/source.js b/1-js/06-advanced-functions/03-closure/9-sort-by-field/_js.view/source.js
index 23b433834..7721d03e2 100644
--- a/1-js/06-advanced-functions/03-closure/9-sort-by-field/_js.view/source.js
+++ b/1-js/06-advanced-functions/03-closure/9-sort-by-field/_js.view/source.js
@@ -1,5 +1,5 @@
-function byField(fieldName){
+function podleVlastnosti(názevVlastnosti){
- // Your code goes here.
+ // Sem přijde váš kód.
}
diff --git a/1-js/06-advanced-functions/03-closure/9-sort-by-field/_js.view/test.js b/1-js/06-advanced-functions/03-closure/9-sort-by-field/_js.view/test.js
index 802f28c4d..62567103a 100644
--- a/1-js/06-advanced-functions/03-closure/9-sort-by-field/_js.view/test.js
+++ b/1-js/06-advanced-functions/03-closure/9-sort-by-field/_js.view/test.js
@@ -1,39 +1,39 @@
-describe("byField", function(){
+describe("podleVlastnosti", function(){
- let users = [
- { name: "John", age: 20, surname: "Johnson" },
- { name: "Pete", age: 18, surname: "Peterson" },
- { name: "Ann", age: 19, surname: "Hathaway" },
+ let uživatelé = [
+ { jméno: "Jan", věk: 20, příjmení: "Janík" },
+ { jméno: "Petr", věk: 18, příjmení: "Petřík" },
+ { jméno: "Anna", věk: 19, příjmení: "Hadrabová" },
];
- it("sorts users by name", function(){
- let nameSortedKey = [
- { name: "Ann", age: 19, surname: "Hathaway" },
- { name: "John", age: 20, surname: "Johnson"},
- { name: "Pete", age: 18, surname: "Peterson" },
+ it("seřadíme uživatele podle jména", function(){
+ let seřazeníPodleJménaKlíč = [
+ { jméno: "Anna", věk: 19, příjmení: "Hadrabová" },
+ { jméno: "Jan", věk: 20, příjmení: "Janík"},
+ { jméno: "Petr", věk: 18, příjmení: "Petřík" },
];
- let nameSortedAnswer = users.sort(byField("name"));
- assert.deepEqual(nameSortedKey, nameSortedAnswer);
+ let seřazeníPodleJménaOdpověď = uživatelé.sort(podleVlastnosti("jméno"));
+ assert.deepEqual(seřazeníPodleJménaKlíč, seřazeníPodleJménaOdpověď);
});
- it("sorts users by age", function(){
- let ageSortedKey = [
- { name: "Pete", age: 18, surname: "Peterson" },
- { name: "Ann", age: 19, surname: "Hathaway" },
- { name: "John", age: 20, surname: "Johnson"},
+ it("seřadíme uživatele podle věku", function(){
+ let seřazeníPodleVěkuKlíč = [
+ { jméno: "Petr", věk: 18, příjmení: "Petřík" },
+ { jméno: "Anna", věk: 19, příjmení: "Hadrabová" },
+ { jméno: "Jan", věk: 20, příjmení: "Janík"},
];
- let ageSortedAnswer = users.sort(byField("age"));
- assert.deepEqual(ageSortedKey, ageSortedAnswer);
+ let seřazeníPodleVěkuOdpověď = uživatelé.sort(podleVlastnosti("věk"));
+ assert.deepEqual(seřazeníPodleVěkuKlíč, seřazeníPodleVěkuOdpověď);
});
- it("sorts users by surname", function(){
- let surnameSortedKey = [
- { name: "Ann", age: 19, surname: "Hathaway" },
- { name: "John", age: 20, surname: "Johnson"},
- { name: "Pete", age: 18, surname: "Peterson" },
+ it("seřadíme uživatele podle příjmení", function(){
+ let seřazeníPodlePříjmeníKlíč = [
+ { jméno: "Anna", věk: 19, příjmení: "Hadrabová" },
+ { jméno: "Jan", věk: 20, příjmení: "Janík"},
+ { jméno: "Petr", věk: 18, příjmení: "Petřík" },
];
- let surnameSortedAnswer = users.sort(byField("surname"));
- assert.deepEqual(surnameSortedAnswer, surnameSortedKey);
+ let seřazeníPodlePříjmeníOdpověď = uživatelé.sort(podleVlastnosti("příjmení"));
+ assert.deepEqual(seřazeníPodlePříjmeníOdpověď, seřazeníPodlePříjmeníKlíč);
});
});
diff --git a/1-js/06-advanced-functions/03-closure/9-sort-by-field/solution.md b/1-js/06-advanced-functions/03-closure/9-sort-by-field/solution.md
index 8b1378917..e69de29bb 100644
--- a/1-js/06-advanced-functions/03-closure/9-sort-by-field/solution.md
+++ b/1-js/06-advanced-functions/03-closure/9-sort-by-field/solution.md
@@ -1 +0,0 @@
-
diff --git a/1-js/06-advanced-functions/03-closure/9-sort-by-field/task.md b/1-js/06-advanced-functions/03-closure/9-sort-by-field/task.md
index 08fb5cc34..517f0aefc 100644
--- a/1-js/06-advanced-functions/03-closure/9-sort-by-field/task.md
+++ b/1-js/06-advanced-functions/03-closure/9-sort-by-field/task.md
@@ -2,35 +2,35 @@ importance: 5
---
-# Sort by field
+# Řazení podle vlastnosti
-We've got an array of objects to sort:
+Máme pole objektů, které chceme seřadit:
```js
-let users = [
- { name: "John", age: 20, surname: "Johnson" },
- { name: "Pete", age: 18, surname: "Peterson" },
- { name: "Ann", age: 19, surname: "Hathaway" }
+let uživatelé = [
+ { jméno: "Jan", věk: 20, příjmení: "Janík" },
+ { jméno: "Petr", věk: 18, příjmení: "Petřík" },
+ { jméno: "Anna", věk: 19, příjmení: "Hadrabová" }
];
```
-The usual way to do that would be:
+Obvyklý způsob, jak to udělat, by byl:
```js
-// by name (Ann, John, Pete)
-users.sort((a, b) => a.name > b.name ? 1 : -1);
+// podle jména (Anna, Jan, Petr)
+uživatelé.sort((a, b) => a.jméno > b.jméno ? 1 : -1);
-// by age (Pete, Ann, John)
-users.sort((a, b) => a.age > b.age ? 1 : -1);
+// podle věku (Petr, Anna, Jan)
+uživatelé.sort((a, b) => a.věk > b.věk ? 1 : -1);
```
-Can we make it even less verbose, like this?
+Můžeme to učinit ještě stručněji, například takto?
```js
-users.sort(byField('name'));
-users.sort(byField('age'));
+uživatelé.sort(podleVlastnosti('jméno'));
+uživatelé.sort(podleVlastnosti('věk'));
```
-So, instead of writing a function, just put `byField(fieldName)`.
+Místo psaní funkce tedy jednoduše napíšeme `podleVlastnosti(názevVlastnosti)`.
-Write the function `byField` that can be used for that.
+Napište funkci `podleVlastnosti`, kterou k tomu můžeme použít.
diff --git a/1-js/06-advanced-functions/03-closure/article.md b/1-js/06-advanced-functions/03-closure/article.md
index cb43a7968..edbc7b343 100644
--- a/1-js/06-advanced-functions/03-closure/article.md
+++ b/1-js/06-advanced-functions/03-closure/article.md
@@ -1,388 +1,387 @@
+# Oblast platnosti proměnné, uzávěr
-# Variable scope, closure
+JavaScript je značně funkcionálně orientovaný jazyk. Dává nám velké množství svobody. Funkci můžeme kdykoli vytvořit, předat ji jako argument jiné funkci a později ji volat z úplně jiného místa kódu.
-JavaScript is a very function-oriented language. It gives us a lot of freedom. A function can be created at any moment, passed as an argument to another function, and then called from a totally different place of code later.
+Víme již, že funkce může přistupovat k proměnným, které leží mimo ni (k „vnějším“ proměnným).
-We already know that a function can access variables outside of it ("outer" variables).
+Co se však stane, když se po vytvoření funkce vnější proměnné změní? Dostanou se do funkce jejich nové, nebo staré hodnoty?
-But what happens if outer variables change since a function is created? Will the function get newer values or the old ones?
+A co když je funkce předána jako argument a pak je volána z jiného místa kódu? Bude mít na novém místě přístup k vnějším proměnným?
-And what if a function is passed along as an argument and called from another place of code, will it get access to outer variables at the new place?
+Rozšiřme si znalosti, abychom porozuměli těmto i složitějším scénářům.
-Let's expand our knowledge to understand these scenarios and more complex ones.
+```smart header="Zde budeme hovořit o proměnných deklarovaných pomocí `let/const`"
+V JavaScriptu jsou tři způsoby, jak deklarovat proměnnou: `let`, `const` (tyto dva jsou moderní) a `var` (pozůstatek minulosti).
-```smart header="We'll talk about `let/const` variables here"
-In JavaScript, there are 3 ways to declare a variable: `let`, `const` (the modern ones), and `var` (the remnant of the past).
-
-- In this article we'll use `let` variables in examples.
-- Variables, declared with `const`, behave the same, so this article is about `const` too.
-- The old `var` has some notable differences, they will be covered in the article .
+- V tomto článku budeme v příkladech používat proměnné deklarované pomocí `let`.
+- Proměnné deklarované pomocí `const` se chovají stejně, takže tento článek platí i pro `const`.
+- Starý příkaz `var` má určité významné rozdíly, které probereme v článku .
```
-## Code blocks
+## Kódové bloky
-If a variable is declared inside a code block `{...}`, it's only visible inside that block.
+Jestliže je proměnná deklarována uvnitř kódového bloku `{...}`, je viditelná jedině uvnitř tohoto bloku.
-For example:
+Příklad:
```js run
{
- // do some job with local variables that should not be seen outside
+ // provedeme nějakou práci s lokálními proměnnými, které nemají být vidět zvenčí
- let message = "Hello"; // only visible in this block
+ let zpráva = "Ahoj"; // je viditelná jen v tomto bloku
- alert(message); // Hello
+ alert(zpráva); // Ahoj
}
-alert(message); // Error: message is not defined
+alert(zpráva); // Chyba: zpráva není definována
```
-We can use this to isolate a piece of code that does its own task, with variables that only belong to it:
+Díky tomu můžeme izolovat část kódu, která odvede svou vlastní práci, s proměnnými, které budou patřit pouze jí:
```js run
{
- // show message
- let message = "Hello";
- alert(message);
+ // zobrazí zprávu
+ let zpráva = "Ahoj";
+ alert(zpráva);
}
{
- // show another message
- let message = "Goodbye";
- alert(message);
+ // zobrazí jinou zprávu
+ let zpráva = "Na shledanou";
+ alert(zpráva);
}
```
-````smart header="There'd be an error without blocks"
-Please note, without separate blocks there would be an error, if we use `let` with the existing variable name:
+````smart header="Bez bloků by nastala chyba"
+Prosíme všimněte si, že bez oddělených bloků by nastala chyba, kdybychom použili `let` s již existujícím názvem proměnné:
```js run
-// show message
-let message = "Hello";
-alert(message);
+// zobrazí zprávu
+let zpráva = "Ahoj";
+alert(zpráva);
-// show another message
+// zobrazí jinou zprávu
*!*
-let message = "Goodbye"; // Error: variable already declared
+let zpráva = "Na shledanou"; // Chyba: proměnná je již deklarována
*/!*
-alert(message);
+alert(zpráva);
```
````
-For `if`, `for`, `while` and so on, variables declared in `{...}` are also only visible inside:
+Také pro `if`, `for`, `while` a podobné jsou proměnné deklarované v `{...}` viditelné jedině uvnitř:
```js run
if (true) {
- let phrase = "Hello!";
+ let věta = "Ahoj!";
- alert(phrase); // Hello!
+ alert(věta); // Ahoj!
}
-alert(phrase); // Error, no such variable!
+alert(věta); // Chyba, taková proměnná neexistuje!
```
-Here, after `if` finishes, the `alert` below won't see the `phrase`, hence the error.
+Zde po skončení `if` funkce `alert` pod ním neuvidí proměnnou `věta`, takže nastane chyba.
-That's great, as it allows us to create block-local variables, specific to an `if` branch.
+To je skvělé, protože nám to umožňuje vytvářet blokově lokální proměnné, specifické pro větev `if`.
-The similar thing holds true for `for` and `while` loops:
+Podobně to platí pro cykly `for` a `while`:
```js run
for (let i = 0; i < 3; i++) {
- // the variable i is only visible inside this for
- alert(i); // 0, then 1, then 2
+ // proměnná i je viditelná jen uvnitř tohoto cyklu for
+ alert(i); // 0, pak 1, pak 2
}
-alert(i); // Error, no such variable
+alert(i); // Chyba, taková proměnná neexistuje
```
-Visually, `let i` is outside of `{...}`. But the `for` construct is special here: the variable, declared inside it, is considered a part of the block.
+Vizuálně je `let i` mimo `{...}`, avšak konstrukt `for` je v tomto ohledu speciální: proměnná, která je deklarována uvnitř něj, se považuje za součást bloku.
-## Nested functions
+## Vnořené funkce
-A function is called "nested" when it is created inside another function.
+Funkce se nazývá „vnořená“, když je vytvořena uvnitř jiné funkce.
-It is easily possible to do this with JavaScript.
+V JavaScriptu je to snadno možné.
-We can use it to organize our code, like this:
+Můžeme to využít k organizaci našeho kódu, například takto:
```js
-function sayHiBye(firstName, lastName) {
+function řekniAhojNashle(křestníJméno, příjmení) {
- // helper nested function to use below
- function getFullName() {
- return firstName + " " + lastName;
+ // pomocná vnořená funkce, kterou použijeme níže
+ function vraťCeléJméno() {
+ return křestníJméno + " " + příjmení;
}
- alert( "Hello, " + getFullName() );
- alert( "Bye, " + getFullName() );
+ alert( "Ahoj, " + vraťCeléJméno() );
+ alert( "Nashle, " + vraťCeléJméno() );
}
```
-Here the *nested* function `getFullName()` is made for convenience. It can access the outer variables and so can return the full name. Nested functions are quite common in JavaScript.
+Zde je *vnořená* funkce `vraťCeléJméno()` vytvořena pro naše pohodlí. Může přistupovat k vnějším proměnným, a tak může vrátit celé jméno. Vnořené funkce jsou v JavaScriptu poměrně běžné.
-What's much more interesting, a nested function can be returned: either as a property of a new object or as a result by itself. It can then be used somewhere else. No matter where, it still has access to the same outer variables.
+Ještě zajímavější je, že vnořenou funkci můžeme vrátit: buď jako vlastnost nového objektu, nebo jako samotný výsledek funkce. Pak ji můžeme použít někde jinde. Ať to bude kdekoli, stále bude mít přístup ke stejným vnějším proměnným.
-Below, `makeCounter` creates the "counter" function that returns the next number on each invocation:
+V následujícím příkladu `vytvořČítač` vytvoří funkci „čítače“, která při každém zavolání vrátí další číslo:
```js run
-function makeCounter() {
- let count = 0;
+function vytvořČítač() {
+ let počet = 0;
return function() {
- return count++;
+ return počet++;
};
}
-let counter = makeCounter();
+let čítač = vytvořČítač();
-alert( counter() ); // 0
-alert( counter() ); // 1
-alert( counter() ); // 2
+alert( čítač() ); // 0
+alert( čítač() ); // 1
+alert( čítač() ); // 2
```
-Despite being simple, slightly modified variants of that code have practical uses, for instance, as a [random number generator](https://en.wikipedia.org/wiki/Pseudorandom_number_generator) to generate random values for automated tests.
+Mírně upravené varianty tohoto kódu, třebaže jsou jednoduché, mají praktické využití, například jako [generátor pseudonáhodných čísel](https://cs.wikipedia.org/wiki/Generátor_pseudonáhodných_čísel), který generuje náhodné hodnoty pro automatizované testy.
-How does this work? If we create multiple counters, will they be independent? What's going on with the variables here?
+Jak to funguje? Když vytvoříme více čítačů, budou nezávislé? Co se bude dít se zdejšími proměnnými?
-Understanding such things is great for the overall knowledge of JavaScript and beneficial for more complex scenarios. So let's go a bit in-depth.
+Porozumět takovým věcem je skvělé pro všeobecnou znalost JavaScriptu a vyplatí se při složitějších scénářích. Pojďme tedy trochu do hloubky.
-## Lexical Environment
+## Lexikální prostředí
-```warn header="Here be dragons!"
-The in-depth technical explanation lies ahead.
+```warn header="Zde jsou draci!"
+Před námi leží hlubší technické vysvětlení.
-As far as I'd like to avoid low-level language details, any understanding without them would be lacking and incomplete, so get ready.
+Jakkoli se snažím vyhnout se nízkoúrovňovým detailům jazyka, bez nich by porozumění bylo děravé a neúplné, takže se na ně připravte.
```
-For clarity, the explanation is split into multiple steps.
+Aby to bylo jasnější, rozdělíme vysvětlení na několik kroků.
-### Step 1. Variables
+### Krok 1. Proměnné
-In JavaScript, every running function, code block `{...}`, and the script as a whole have an internal (hidden) associated object known as the *Lexical Environment*.
+V JavaScriptu je ke každé spuštěné funkci, kódovému bloku `{...}` i celému skriptu připojen interní (skrytý) objekt, nazývaný *lexikální prostředí*.
-The Lexical Environment object consists of two parts:
+Objekt lexikálního prostředí se skládá ze dvou částí:
-1. *Environment Record* -- an object that stores all local variables as its properties (and some other information like the value of `this`).
-2. A reference to the *outer lexical environment*, the one associated with the outer code.
+1. *Záznam prostředí* -- objekt, v němž jsou uloženy všechny lokální proměnné jako jeho vlastnosti (a některé další informace, např. hodnota `this`).
+2. Odkaz na *vnější lexikální prostředí*, tedy to, které je spojeno s vnějším kódem.
-**A "variable" is just a property of the special internal object, `Environment Record`. "To get or change a variable" means "to get or change a property of that object".**
+**„Proměnná“ je jen vlastnost speciálního interního objektu, `záznamu prostředí`. „Načíst nebo změnit proměnnou“ znamená „načíst nebo změnit vlastnost tohoto objektu“.**
-In this simple code without functions, there is only one Lexical Environment:
+V tomto jednoduchém kódu bez funkcí existuje pouze jedno lexikální prostředí:
-
+
-This is the so-called *global* Lexical Environment, associated with the whole script.
+To je tzv. *globální* lexikální prostředí, připojené k celému skriptu.
-On the picture above, the rectangle means Environment Record (variable store) and the arrow means the outer reference. The global Lexical Environment has no outer reference, that's why the arrow points to `null`.
+Obdélník v uvedeném obrázku znamená záznam prostředí (skladiště proměnných) a šipka znamená odkaz na vnější prostředí. Globální lexikální prostředí nemá žádný odkaz na vnější prostředí, proto šipka ukazuje na `null`.
-As the code starts executing and goes on, the Lexical Environment changes.
+Když se kód začne provádět, lexikální prostředí se s jeho během mění.
-Here's a little bit longer code:
+Zde je trochu delší kód:
-
+
-Rectangles on the right-hand side demonstrate how the global Lexical Environment changes during the execution:
+Obdélníky napravo ukazují, jak se globální lexikální prostředí mění během provádění kódu:
-1. When the script starts, the Lexical Environment is pre-populated with all declared variables.
- - Initially, they are in the "Uninitialized" state. That's a special internal state, it means that the engine knows about the variable, but it cannot be referenced until it has been declared with `let`. It's almost the same as if the variable didn't exist.
-2. Then `let phrase` definition appears. There's no assignment yet, so its value is `undefined`. We can use the variable from this point forward.
-3. `phrase` is assigned a value.
-4. `phrase` changes the value.
+1. Když se skript spustí, lexikální prostředí se obsadí všemi deklarovanými proměnnými.
+ - Na začátku jsou ve stavu „neinicializováno“. To je speciální vnitřní stav, který znamená, že motor ví o proměnné, ale nelze se na ni odkazovat, dokud nebude deklarována pomocí `let`. Je to skoro totéž, jako by proměnná neexistovala.
+2. Pak se objeví definice `let věta`. Zatím zde není žádné přiřazení, takže hodnota proměnné je `undefined`. Od této chvíle můžeme tuto proměnnou používat.
+3. Do proměnné `věta` je přiřazena hodnota.
+4. Hodnota proměnné `věta` se změní.
-Everything looks simple for now, right?
+Prozatím to všechno vypadá jednoduše, že?
-- A variable is a property of a special internal object, associated with the currently executing block/function/script.
-- Working with variables is actually working with the properties of that object.
+- Proměnná je vlastností speciálního interního objektu, připojeného k právě vykonávanému bloku/funkci/skriptu.
+- Práce s proměnnými je ve skutečnosti práce s vlastnostmi tohoto objektu.
-```smart header="Lexical Environment is a specification object"
-"Lexical Environment" is a specification object: it only exists "theoretically" in the [language specification](https://tc39.es/ecma262/#sec-lexical-environments) to describe how things work. We can't get this object in our code and manipulate it directly.
+```smart header="Lexikální prostředí je objekt ze specifikace"
+„Lexikální prostředí“ je objekt ze specifikace: existuje jen „teoreticky“ ve [specifikaci jazyka](https://tc39.es/ecma262/#sec-lexical-environments), aby popisoval, jak vše funguje. V našem kódu nemůžeme tento objekt získat a přímo s ním manipulovat.
-JavaScript engines also may optimize it, discard variables that are unused to save memory and perform other internal tricks, as long as the visible behavior remains as described.
+Motory JavaScriptu jej také mohou optimalizovat, vyřazovat nepoužívané proměnné, aby ušetřily paměť, a provádět jiné vnitřní triky, pokud jeho viditelné chování zůstává takové, jak je zde popsáno.
```
-### Step 2. Function Declarations
+### Krok 2. Deklarace funkcí
-A function is also a value, like a variable.
+Funkce je také hodnota, stejně jako proměnná.
-**The difference is that a Function Declaration is instantly fully initialized.**
+**Rozdíl je v tom, že při deklaraci je funkce okamžitě plně inicializována.**
-When a Lexical Environment is created, a Function Declaration immediately becomes a ready-to-use function (unlike `let`, that is unusable till the declaration).
+Když je vytvořeno lexikální prostředí, deklarace funkce okamžitě vytvoří funkci připravenou k použití (na rozdíl od proměnné v `let`, která je před deklarací nepoužitelná).
-That's why we can use a function, declared as Function Declaration, even before the declaration itself.
+Z tohoto důvodu můžeme používat funkci, deklarovanou deklarací funkce, ještě před samotnou deklarací.
-For example, here's the initial state of the global Lexical Environment when we add a function:
+Například zde je úvodní stav globálního lexikálního prostředí, když přidáme funkci:

-Naturally, this behavior only applies to Function Declarations, not Function Expressions where we assign a function to a variable, such as `let say = function(name)...`.
+Pochopitelně toto chování platí jen pro deklarace funkcí, ne pro funkční výrazy, v nichž přiřazujeme funkci do proměnné, například `let řekni = function(jméno)...`.
-### Step 3. Inner and outer Lexical Environment
+### Krok 3. Vnitřní a vnější lexikální prostředí
-When a function runs, at the beginning of the call, a new Lexical Environment is created automatically to store local variables and parameters of the call.
+Když se spustí funkce, na začátku jejího volání je automaticky vytvořeno nové lexikální prostředí, do něhož se ukládají lokální proměnné a parametry volání.
-For instance, for `say("John")`, it looks like this (the execution is at the line, labelled with an arrow):
+Například pro `řekni("Jan")` vypadá takto (běh je na řádku označeném šipkou):

-During the function call we have two Lexical Environments: the inner one (for the function call) and the outer one (global):
+Během volání funkce máme dvě lexikální prostředí: vnitřní (pro volání funkce) a vnější (globální):
-- The inner Lexical Environment corresponds to the current execution of `say`. It has a single property: `name`, the function argument. We called `say("John")`, so the value of the `name` is `"John"`.
-- The outer Lexical Environment is the global Lexical Environment. It has the `phrase` variable and the function itself.
+- Vnitřní lexikální prostředí odpovídá aktuálnímu běhu funkce `řekni`. Má jedinou vlastnost: `jméno`, argument funkce. Voláme ji `řekni("Jan")`, takže hodnota vlastnosti `jméno` je `"Jan"`.
+- Vnější lexikální prostředí je globální lexikální prostředí. Má proměnnou `věta` a samotnou funkci.
-The inner Lexical Environment has a reference to the `outer` one.
+Vnitřní lexikální prostředí obsahuje odkaz `outer` na vnější.
-**When the code wants to access a variable -- the inner Lexical Environment is searched first, then the outer one, then the more outer one and so on until the global one.**
+**Když kód chce přistupovat k proměnné -- nejprve se prohledá vnitřní lexikální prostředí, pak vnější, pak ještě vnější a tak dále, až ke globálnímu.**
-If a variable is not found anywhere, that's an error in strict mode (without `use strict`, an assignment to a non-existing variable creates a new global variable, for compatibility with old code).
+Není-li proměnná nikde nalezena, ve striktním režimu nastane chyba (bez `use strict` přiřazení do neexistující proměnné vytvoří novou globální proměnnou, aby byla zachována kompatibilita se starým kódem).
-In this example the search proceeds as follows:
+V tomto příkladu hledání postupuje následovně:
-- For the `name` variable, the `alert` inside `say` finds it immediately in the inner Lexical Environment.
-- When it wants to access `phrase`, then there is no `phrase` locally, so it follows the reference to the outer Lexical Environment and finds it there.
+- Co se týče proměnné `jméno`, `alert` uvnitř `řekni` ji najde okamžitě ve vnitřním lexikálním prostředí.
+- Když chce přistupovat k proměnné `věta`, pak lokálně žádnou proměnnou `věta` nenajde, takže pokračuje odkazem na vnější lexikální prostředí a najde ji v něm.
-
+
-### Step 4. Returning a function
+### Krok 4. Vrácení funkce
-Let's return to the `makeCounter` example.
+Vraťme se k příkladu `vytvořČítač`.
```js
-function makeCounter() {
- let count = 0;
+function vytvořČítač() {
+ let počet = 0;
return function() {
- return count++;
+ return počet++;
};
}
-let counter = makeCounter();
+let čítač = vytvořČítač();
```
-At the beginning of each `makeCounter()` call, a new Lexical Environment object is created, to store variables for this `makeCounter` run.
+Na začátku každého volání `vytvořČítač()` se vytvoří nový objekt lexikálního prostředí, do něhož se uloží proměnné pro tento běh funkce `vytvořČítač`.
-So we have two nested Lexical Environments, just like in the example above:
+Máme tedy dvě vnořená lexikální prostředí, podobně jako ve výše uvedeném příkladu:

-What's different is that, during the execution of `makeCounter()`, a tiny nested function is created of only one line: `return count++`. We don't run it yet, only create.
+Rozdíl spočívá v tom, že během provádění funkce `vytvořČítač()` se vytvoří drobná vnořená funkce tvořená jediným řádkem: `return počet++`. Tuto funkci zatím nevoláme, jenom ji vytvoříme.
-All functions remember the Lexical Environment in which they were made. Technically, there's no magic here: all functions have the hidden property named `[[Environment]]`, that keeps the reference to the Lexical Environment where the function was created:
+Všechny funkce si pamatují lexikální prostředí, v němž byly vytvořeny. Technicky v tom není nic magického: všechny funkce mají skrytou vlastnost jménem `[[Environment]]`, která si udržuje odkaz na lexikální prostředí, v němž byla funkce vytvořena:

-So, `counter.[[Environment]]` has the reference to `{count: 0}` Lexical Environment. That's how the function remembers where it was created, no matter where it's called. The `[[Environment]]` reference is set once and forever at function creation time.
+Takže `čítač.[[Environment]]` má odkaz na lexikální prostředí `{počet: 0}`. Tímto způsobem si funkce pamatuje, kde byla vytvořena, bez ohledu na to, kde je volána. Odkaz `[[Environment]]` se při vytvoření funkce nastaví jednou provždy.
-Later, when `counter()` is called, a new Lexical Environment is created for the call, and its outer Lexical Environment reference is taken from `counter.[[Environment]]`:
+Když je `čítač()` později volán, vytvoří se pro toto volání nové lexikální prostředí a odkaz na jeho vnější lexikální prostředí se převezme z `čítač.[[Environment]]`:

-Now when the code inside `counter()` looks for `count` variable, it first searches its own Lexical Environment (empty, as there are no local variables there), then the Lexical Environment of the outer `makeCounter()` call, where it finds and changes it.
+Když nyní kód uvnitř funkce `čítač()` hledá proměnnou `počet`, nejprve prohledá své vlastní lexikální prostředí (prázdné, jelikož tady nejsou žádné lokální proměnné), pak lexikální prostředí vnějšího volání `vytvořČítač()`, kde ji najde a změní.
-**A variable is updated in the Lexical Environment where it lives.**
+**Proměnná je změněna v lexikálním prostředí, v němž přebývá.**
-Here's the state after the execution:
+Zde je stav po provedení funkce:

-If we call `counter()` multiple times, the `count` variable will be increased to `2`, `3` and so on, at the same place.
+Jestliže voláme `čítač()` vícekrát, proměnná `počet` se zvýší na `2`, `3` a tak dále, a to na stejném místě.
-```smart header="Closure"
-There is a general programming term "closure", that developers generally should know.
+```smart header="Uzávěr"
+Existuje obecný programovací pojem „uzávěr“, který by vývojáři obecně měli znát.
-A [closure](https://en.wikipedia.org/wiki/Closure_(computer_programming)) is a function that remembers its outer variables and can access them. In some languages, that's not possible, or a function should be written in a special way to make it happen. But as explained above, in JavaScript, all functions are naturally closures (there is only one exception, to be covered in ).
+[Uzávěr](https://cs.wikipedia.org/wiki/Uz%C3%A1v%C4%9Br_(programov%C3%A1n%C3%AD)) je funkce, která si pamatuje své vnější proměnné a může k nim přistupovat. V některých jazycích to není možné nebo funkce musí být napsána speciálním způsobem, aby se to mohlo dít. Ale jak bylo vysvětleno výše, v JavaScriptu jsou všechny funkce přirozeně uzávěry (je tady jen jedna výjimka, kterou probereme v kapitole ).
-That is: they automatically remember where they were created using a hidden `[[Environment]]` property, and then their code can access outer variables.
+To znamená: pomocí skryté vlastnosti `[[Environment]]` si automaticky pamatují, kde byly vytvořeny, a jejich kód pak může přistupovat k vnějším proměnným.
-When on an interview, a frontend developer gets a question about "what's a closure?", a valid answer would be a definition of the closure and an explanation that all functions in JavaScript are closures, and maybe a few more words about technical details: the `[[Environment]]` property and how Lexical Environments work.
+Kdyby front-end vývojář v rozhovoru dostal otázku „co je to uzávěr?“, správná odpověď by byla definice uzávěru a vysvětlení, že v JavaScriptu jsou všechny funkce uzávěry, a možná několik dalších slov o technických detailech: o vlastnosti `[[Environment]]` a o tom, jak fungují lexikální prostředí.
```
-## Garbage collection
+## Sběr odpadků
-Usually, a Lexical Environment is removed from memory with all the variables after the function call finishes. That's because there are no references to it. As any JavaScript object, it's only kept in memory while it's reachable.
+Lexikální prostředí funkce je zpravidla odstraněno z paměti i se všemi proměnnými poté, co volání funkce skončí. Je to proto, že pak už na ně neexistují žádné odkazy. Stejně jako všechny objekty v JavaScriptu je udržováno v paměti, jen dokud je dosažitelné.
-However, if there's a nested function that is still reachable after the end of a function, then it has `[[Environment]]` property that references the lexical environment.
+Jestliže však existuje vnořená funkce, která je po skončení funkce stále dosažitelná, pak tato funkce má vlastnost `[[Environment]]`, která se na toto lexikální prostředí odkazuje.
-In that case the Lexical Environment is still reachable even after the completion of the function, so it stays alive.
+V takovém případě je lexikální prostředí stále dostupné i po skončení funkce, takže bude nadále existovat.
-For example:
+Například:
```js
function f() {
- let value = 123;
+ let hodnota = 123;
return function() {
- alert(value);
+ alert(hodnota);
}
}
-let g = f(); // g.[[Environment]] stores a reference to the Lexical Environment
-// of the corresponding f() call
+let g = f(); // g.[[Environment]] si uloží odkaz na lexikální prostředí
+ // příslušného volání f()
```
-Please note that if `f()` is called many times, and resulting functions are saved, then all corresponding Lexical Environment objects will also be retained in memory. In the code below, all 3 of them:
+Prosíme všimněte si, že je-li `f()` volána mnohokrát a výsledné funkce jsou někam uloženy, pak zůstanou v paměti i všechny příslušné objekty lexikálních prostředí. V následujícím kódu to budou všechny tři:
```js
function f() {
- let value = Math.random();
+ let hodnota = Math.random();
- return function() { alert(value); };
+ return function() { alert(hodnota); };
}
-// 3 functions in array, every one of them links to Lexical Environment
-// from the corresponding f() run
-let arr = [f(), f(), f()];
+// 3 funkce v poli, každá z nich se odkazuje na lexikální prostředí
+// z příslušného spuštění f()
+let pole = [f(), f(), f()];
```
-A Lexical Environment object dies when it becomes unreachable (just like any other object). In other words, it exists only while there's at least one nested function referencing it.
+Objekt lexikálního prostředí je zničen, když se stane nedosažitelným (stejně jako každý jiný objekt). Jinými slovy, bude existovat, jen dokud bude existovat nejméně jedna vnořená funkce, která se na něj odkazuje.
-In the code below, after the nested function is removed, its enclosing Lexical Environment (and hence the `value`) is cleaned from memory:
+V následujícím kódu je po odstranění vnořené funkce její uzavírající lexikální prostředí (a tedy i `hodnota`) vymazáno z paměti:
```js
function f() {
- let value = 123;
+ let hodnota = 123;
return function() {
- alert(value);
+ alert(hodnota);
}
}
-let g = f(); // while g function exists, the value stays in memory
+let g = f(); // dokud existuje funkce g, hodnota zůstane v paměti
-g = null; // ...and now the memory is cleaned up
+g = null; // ...a nyní bude paměť pročištěna
```
-### Real-life optimizations
+### Optimalizace v reálném životě
-As we've seen, in theory while a function is alive, all outer variables are also retained.
+Jak jsme viděli, teoreticky dokud funkce existuje, jsou udržovány i všechny vnější proměnné.
-But in practice, JavaScript engines try to optimize that. They analyze variable usage and if it's obvious from the code that an outer variable is not used -- it is removed.
+V praxi se však JavaScriptové motory snaží o optimalizaci. Analyzují používání proměnných, a je-li z kódu zřejmé, že vnější proměnná není nikde použita, bude odstraněna.
-**An important side effect in V8 (Chrome, Edge, Opera) is that such variable will become unavailable in debugging.**
+**Důležitý vedlejší efekt ve V8 (Chrome, Edge, Opera) je, že taková proměnná přestane být dostupná při ladění.**
-Try running the example below in Chrome with the Developer Tools open.
+Zkuste si spustit níže uvedený příklad v Chrome s otevřenými vývojářskými nástroji.
-When it pauses, in the console type `alert(value)`.
+Když se zastaví, v konzoli zadejte `alert(hodnota)`.
```js run
function f() {
- let value = Math.random();
+ let hodnota = Math.random();
function g() {
- debugger; // in console: type alert(value); No such variable!
+ debugger; // v konzoli zadejte: alert(hodnota); taková proměnná neexistuje!
}
return g;
@@ -392,18 +391,18 @@ let g = f();
g();
```
-As you could see -- there is no such variable! In theory, it should be accessible, but the engine optimized it out.
+Jak vidíme -- taková proměnná neexistuje! Teoreticky by měla být dostupná, ale motor ji vyřadil při optimalizaci.
-That may lead to funny (if not such time-consuming) debugging issues. One of them -- we can see a same-named outer variable instead of the expected one:
+To může vést k zábavným (kdyby nezabíraly tolik času) problémům při ladění. Jeden z nich -- můžeme vidět vnější proměnnou se stejným názvem namísto očekávané:
```js run global
-let value = "Surprise!";
+let hodnota = "Překvapení!";
function f() {
- let value = "the closest value";
+ let hodnota = "nejbližší hodnota";
function g() {
- debugger; // in console: type alert(value); Surprise!
+ debugger; // v konzoli zadejte: alert(hodnota); Překvapení!
}
return g;
@@ -413,6 +412,6 @@ let g = f();
g();
```
-This feature of V8 is good to know. If you are debugging with Chrome/Edge/Opera, sooner or later you will meet it.
+Tuto vlastnost V8 je dobré znát. Jestliže ladíte v Chrome, Edge nebo Opeře, dříve nebo později se s ní setkáte.
-That is not a bug in the debugger, but rather a special feature of V8. Perhaps it will be changed sometime. You can always check for it by running the examples on this page.
+Není to chyba ladicího nástroje, ale spíše speciální vlastnost V8. Možná bude časem změněna. Vždy si ji můžete ověřit spuštěním příkladů na této stránce.
diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-2.svg b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-2.svg
index f37488537..8c9abe9f5 100644
--- a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-2.svg
+++ b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-2.svg
@@ -1 +1 @@
-
\ No newline at end of file
+
\ No newline at end of file
diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-6.svg b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-6.svg
index 06d5b5060..289cacf90 100644
--- a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-6.svg
+++ b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-6.svg
@@ -1 +1 @@
-
\ No newline at end of file
+
\ No newline at end of file
diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-global-2.svg b/1-js/06-advanced-functions/03-closure/lexical-environment-global-2.svg
index b6e576f0c..8572e73ab 100644
--- a/1-js/06-advanced-functions/03-closure/lexical-environment-global-2.svg
+++ b/1-js/06-advanced-functions/03-closure/lexical-environment-global-2.svg
@@ -1 +1 @@
-
\ No newline at end of file
+
\ No newline at end of file
diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-global-3.svg b/1-js/06-advanced-functions/03-closure/lexical-environment-global-3.svg
index 1942a7e37..ec8c57a33 100644
--- a/1-js/06-advanced-functions/03-closure/lexical-environment-global-3.svg
+++ b/1-js/06-advanced-functions/03-closure/lexical-environment-global-3.svg
@@ -1 +1 @@
-
\ No newline at end of file
+
\ No newline at end of file
diff --git a/1-js/06-advanced-functions/04-var/article.md b/1-js/06-advanced-functions/04-var/article.md
index 28d7a76ec..104045df6 100644
--- a/1-js/06-advanced-functions/04-var/article.md
+++ b/1-js/06-advanced-functions/04-var/article.md
@@ -1,287 +1,287 @@
-# The old "var"
+# Starý příkaz „var“
-```smart header="This article is for understanding old scripts"
-The information in this article is useful for understanding old scripts.
+```smart header="Tento článek slouží k pochopení starých skriptů"
+Informace v tomto článku jsou užitečné k tomu, abyste porozuměli starým skriptům.
-That's not how we write new code.
+Není to způsob, jak psát nový kód.
```
-In the very first chapter about [variables](info:variables), we mentioned three ways of variable declaration:
+V úplně první kapitole o [proměnných](info:variables) jsme zmínili tři způsoby deklarace proměnných:
1. `let`
2. `const`
3. `var`
-The `var` declaration is similar to `let`. Most of the time we can replace `let` by `var` or vice-versa and expect things to work:
+Deklarace `var` je podobná `let`. Ve většině případů můžeme nahradit `let` za `var` nebo naopak a očekávat, že vše bude fungovat:
```js run
-var message = "Hi";
-alert(message); // Hi
+var zpráva = "Ahoj";
+alert(zpráva); // Ahoj
```
-But internally `var` is a very different beast, that originates from very old times. It's generally not used in modern scripts, but still lurks in the old ones.
+Vnitřně je však `var` velmi odlišná potvůrka, která pochází z dřívějších časů. V moderních skriptech se obvykle nepoužívá, ale ve starých stále číhá.
-If you don't plan on meeting such scripts you may even skip this chapter or postpone it.
+Pokud neplánujete se s takovými skripty setkat, můžete tuto kapitolu přeskočit nebo odložit na později.
-On the other hand, it's important to understand differences when migrating old scripts from `var` to `let`, to avoid odd errors.
+Naproti tomu, když převádíte staré skripty z `var` na `let`, je důležité porozumět rozdílům, abyste se vyhnuli podivným chybám.
-## "var" has no block scope
+## „var“ nemá blokovou platnost
-Variables, declared with `var`, are either function-scoped or global-scoped. They are visible through blocks.
+Proměnné deklarované pomocí `var` mají rozsah platnosti buď funkční, nebo globální. Jsou viditelné i skrz bloky.
-For instance:
+Například:
```js run
if (true) {
- var test = true; // use "var" instead of "let"
+ var test = true; // použijeme „var“ namísto „let“
}
*!*
-alert(test); // true, the variable lives after if
+alert(test); // true, proměnná existuje i za if
*/!*
```
-As `var` ignores code blocks, we've got a global variable `test`.
+Protože `var` ignoruje kódové bloky, vytvořili jsme globální proměnnou `test`.
-If we used `let test` instead of `var test`, then the variable would only be visible inside `if`:
+Kdybychom použili `let test` namísto `var test`, pak by tato proměnná byla viditelná jen uvnitř `if`:
```js run
if (true) {
- let test = true; // use "let"
+ let test = true; // použijeme „let“
}
*!*
-alert(test); // ReferenceError: test is not defined
+alert(test); // ReferenceError: test není definován
*/!*
```
-The same thing for loops: `var` cannot be block- or loop-local:
+Totéž platí pro cykly: `var` nemůže být lokální v bloku nebo ve smyčce:
```js run
for (var i = 0; i < 10; i++) {
- var one = 1;
+ var jedna = 1;
// ...
}
*!*
-alert(i); // 10, "i" is visible after loop, it's a global variable
-alert(one); // 1, "one" is visible after loop, it's a global variable
+alert(i); // 10, „i“ je viditelná i za cyklem, je to globální proměnná
+alert(jedna); // 1, „jedna“ je viditelná i za cyklem, je to globální proměnná
*/!*
```
-If a code block is inside a function, then `var` becomes a function-level variable:
+Nachází-li se kódový blok uvnitř funkce, pak `var` deklaruje proměnnou na úrovni funkce:
```js run
-function sayHi() {
+function řekniAhoj() {
if (true) {
- var phrase = "Hello";
+ var věta = "Ahoj";
}
- alert(phrase); // works
+ alert(věta); // funguje
}
-sayHi();
-alert(phrase); // ReferenceError: phrase is not defined
+řekniAhoj();
+alert(věta); // ReferenceError: věta není definována
```
-As we can see, `var` pierces through `if`, `for` or other code blocks. That's because a long time ago in JavaScript, blocks had no Lexical Environments, and `var` is a remnant of that.
+Jak vidíme, `var` se probije skrz `if`, `for` a jiné kódové bloky. Je to proto, že před dlouhou dobou bloky v JavaScriptu neměly lexikální prostředí a `var` je toho pozůstatkem.
-## "var" tolerates redeclarations
+## „var“ toleruje opakované deklarace
-If we declare the same variable with `let` twice in the same scope, that's an error:
+Jestliže deklarujeme stejnou proměnnou pomocí `let` ve stejné oblasti dvakrát, nastane chyba:
```js run
-let user;
-let user; // SyntaxError: 'user' has already been declared
+let uživatel;
+let uživatel; // SyntaxError: 'uživatel' již byl deklarován
```
-With `var`, we can redeclare a variable any number of times. If we use `var` with an already-declared variable, it's just ignored:
+Pomocí `var` můžeme znovu deklarovat proměnnou, kolikrát chceme. Použijeme-li `var` s již deklarovanou proměnnou, bude ignorováno:
```js run
-var user = "Pete";
+var uživatel = "Petr";
-var user = "John"; // this "var" does nothing (already declared)
-// ...it doesn't trigger an error
+var uživatel = "Jan"; // tento „var“ neudělá nic (proměnná je již deklarována)
+// ...nevyvolá chybu
-alert(user); // John
+alert(uživatel); // Jan
```
-## "var" variables can be declared below their use
+## Pomocí „var“ můžeme proměnné deklarovat až po jejich použití
-`var` declarations are processed when the function starts (or script starts for globals).
+Deklarace `var` se zpracovávají, když se funkce spustí (nebo když se spustí skript, jsou-li globální).
-In other words, `var` variables are defined from the beginning of the function, no matter where the definition is (assuming that the definition is not in the nested function).
+Jinými slovy, proměnné deklarované pomocí `var` jsou definovány od začátku funkce bez ohledu na to, kde se jejich definice nachází (za předpokladu, že definice není uvnitř vnořené funkce).
-So this code:
+Takže tento kód:
```js run
-function sayHi() {
- phrase = "Hello";
+function řekniAhoj() {
+ věta = "Ahoj";
- alert(phrase);
+ alert(věta);
*!*
- var phrase;
+ var věta;
*/!*
}
-sayHi();
+řekniAhoj();
```
-...Is technically the same as this (moved `var phrase` above):
+...je technicky stejný jako tento (přesuneme `var věta` nahoru):
```js run
-function sayHi() {
+function řekniAhoj() {
*!*
- var phrase;
+ var věta;
*/!*
- phrase = "Hello";
+ věta = "Ahoj";
- alert(phrase);
+ alert(věta);
}
-sayHi();
+řekniAhoj();
```
-...Or even as this (remember, code blocks are ignored):
+...Nebo i jako tento (pamatujte, že kódové bloky jsou ignorovány):
```js run
-function sayHi() {
- phrase = "Hello"; // (*)
+function řekniAhoj() {
+ věta = "Ahoj"; // (*)
*!*
if (false) {
- var phrase;
+ var věta;
}
*/!*
- alert(phrase);
+ alert(věta);
}
-sayHi();
+řekniAhoj();
```
-People also call such behavior "hoisting" (raising), because all `var` are "hoisted" (raised) to the top of the function.
+Takovému chování se někdy říká „stoupání“ (anglicky „hoisting“ nebo „raising“), jelikož každý `var` „vystoupá“ („hoist“, „raise“) až k vrcholu funkce.
-So in the example above, `if (false)` branch never executes, but that doesn't matter. The `var` inside it is processed in the beginning of the function, so at the moment of `(*)` the variable exists.
+V uvedeném příkladu se větev `if (false)` nikdy nespustí, ale na tom nezáleží. Příkaz `var` uvnitř se zpracuje na začátku funkce, takže v okamžiku provedení řádku `(*)` proměnná existuje.
-**Declarations are hoisted, but assignments are not.**
+**Deklarace stoupají, ale přiřazení ne.**
-That's best demonstrated with an example:
+Nejlépe to uvidíme na příkladu:
```js run
-function sayHi() {
- alert(phrase);
+function řekniAhoj() {
+ alert(věta);
*!*
- var phrase = "Hello";
+ var věta = "Ahoj";
*/!*
}
-sayHi();
+řekniAhoj();
```
-The line `var phrase = "Hello"` has two actions in it:
+Řádek `var věta = "Ahoj"` má v sobě dvě akce:
-1. Variable declaration `var`
-2. Variable assignment `=`.
+1. Deklaraci proměnné `var`.
+2. Přiřazení proměnné `=`.
-The declaration is processed at the start of function execution ("hoisted"), but the assignment always works at the place where it appears. So the code works essentially like this:
+Deklarace se vykonává na začátku spuštění funkce („stoupání“), ale přiřazení se provede vždy na místě, na němž se objevilo. Kód tedy funguje v zásadě následovně:
```js run
-function sayHi() {
+function řekniAhoj() {
*!*
- var phrase; // declaration works at the start...
+ var věta; // deklarace se provede na začátku...
*/!*
- alert(phrase); // undefined
+ alert(věta); // undefined
*!*
- phrase = "Hello"; // ...assignment - when the execution reaches it.
+ věta = "Ahoj"; // ...přiřazení - když se běh dostane k němu.
*/!*
}
-sayHi();
+řekniAhoj();
```
-Because all `var` declarations are processed at the function start, we can reference them at any place. But variables are undefined until the assignments.
+Protože všechny deklarace `var` se zpracovávají na začátku funkce, můžeme je uvádět kdekoli. Ale proměnné jsou až do přiřazení nedefinované.
-In both examples above, `alert` runs without an error, because the variable `phrase` exists. But its value is not yet assigned, so it shows `undefined`.
+V obou uvedených příkladech se `alert` spustí bez chyby, protože proměnná `věta` existuje. Ale ještě jí není přiřazena hodnota, takže se zobrazí `undefined`.
## IIFE
-In the past, as there was only `var`, and it has no block-level visibility, programmers invented a way to emulate it. What they did was called "immediately-invoked function expressions" (abbreviated as IIFE).
+V minulosti, kdy bylo jenom `var` a neexistovala viditelnost na úrovni bloku, programátoři vymysleli způsob, jak ji emulovat. To, co vynalezli, bylo nazváno „okamžitě volané funkční výrazy“ („immediately-invoked function expressions“), zkráceně IIFE.
-That's not something we should use nowadays, but you can find them in old scripts.
+Není to nic, co bychom měli používat v současnosti, ale ve starých skriptech je stále můžete najít.
-An IIFE looks like this:
+IIFE vypadá následovně:
```js run
(function() {
- var message = "Hello";
+ var zpráva = "Ahoj";
- alert(message); // Hello
+ alert(zpráva); // Ahoj
})();
```
-Here, a Function Expression is created and immediately called. So the code executes right away and has its own private variables.
+Zde se vytvoří a okamžitě zavolá funkční výraz. Kód se tedy okamžitě spustí a má své vlastní soukromé proměnné.
-The Function Expression is wrapped with parenthesis `(function {...})`, because when JavaScript engine encounters `"function"` in the main code, it understands it as the start of a Function Declaration. But a Function Declaration must have a name, so this kind of code will give an error:
+Funkční výraz je uzavřen do závorek `(function {...})`, protože když motor JavaScriptu narazí v hlavním kódu na `„function“`, chápe to jako začátek deklarace funkce. Avšak deklarace funkce musí obsahovat název, takže tento kód vyvolá chybu:
```js run
-// Tries to declare and immediately call a function
-function() { // <-- SyntaxError: Function statements require a function name
+// Snaží se deklarovat a okamžitě zavolat funkci
+function() { // <-- SyntaxError: Deklarace funkce vyžaduje název funkce
- var message = "Hello";
+ var zpráva = "Ahoj";
- alert(message); // Hello
+ alert(zpráva); // Ahoj
}();
```
-Even if we say: "okay, let's add a name", that won't work, as JavaScript does not allow Function Declarations to be called immediately:
+I kdybychom si řekli: „dobře, tak přidáme název“, nebude to fungovat, protože JavaScript neumožňuje, aby byla deklarace funkce okamžitě volána:
```js run
-// syntax error because of parentheses below
-function go() {
+// závorky níže způsobí syntaktickou chybu
+function jdi() {
-}(); // <-- can't call Function Declaration immediately
+}(); // <-- deklaraci funkce nemůžeme okamžitě volat
```
-So, the parentheses around the function is a trick to show JavaScript that the function is created in the context of another expression, and hence it's a Function Expression: it needs no name and can be called immediately.
+Závorky kolem funkce jsou tedy trik, jak ukázat JavaScriptu, že funkce je vytvořena v kontextu jiného výrazu, a proto je to funkční výraz: nemusí mít název a může být okamžitě zavolán.
-There exist other ways besides parentheses to tell JavaScript that we mean a Function Expression:
+Kromě závorek existují i jiné způsoby, jak oznámit JavaScriptu, že máme na mysli funkční výraz:
```js run
-// Ways to create IIFE
+// Způsoby vytvoření IIFE
*!*(*/!*function() {
- alert("Parentheses around the function");
+ alert("Závorky okolo funkce");
}*!*)*/!*();
*!*(*/!*function() {
- alert("Parentheses around the whole thing");
+ alert("Závorky okolo toho všeho");
}()*!*)*/!*;
*!*!*/!*function() {
- alert("Bitwise NOT operator starts the expression");
+ alert("Bitový operátor NOT zahajuje výraz");
}();
*!*+*/!*function() {
- alert("Unary plus starts the expression");
+ alert("Unární plus zahajuje výraz");
}();
```
-In all the above cases we declare a Function Expression and run it immediately. Let's note again: nowadays there's no reason to write such code.
+Ve všech uvedených případech deklarujeme funkční výraz a okamžitě jej zavoláme. Znovu opakujeme, že v dnešní době není důvod takový kód psát.
-## Summary
+## Shrnutí
-There are two main differences of `var` compared to `let/const`:
+Mezi `var` a `let/const` existují dva hlavní rozdíly:
-1. `var` variables have no block scope, their visibility is scoped to current function, or global, if declared outside function.
-2. `var` declarations are processed at function start (script start for globals).
+1. Proměnné deklarované pomocí `var` nemají blokovou platnost a oblast jejich viditelnosti je celá aktuální funkce. Jsou-li deklarovány mimo funkci, jsou globální.
+2. Deklarace `var` se zpracovávají na začátku funkce (globální deklarace na začátku skriptu).
-There's one more very minor difference related to the global object, that we'll cover in the next chapter.
+Existuje ještě jeden velmi drobný rozdíl vztahující se ke globálnímu objektu, který probereme v příští kapitole.
-These differences make `var` worse than `let` most of the time. Block-level variables is such a great thing. That's why `let` was introduced in the standard long ago, and is now a major way (along with `const`) to declare a variable.
+Kvůli těmto rozdílům je `var` ve většině případů horší než `let`. Proměnné na úrovni bloku jsou vynikající věc. To je důvod, proč bylo do standardu již před dlouhou dobou zavedeno `let` a nyní je hlavním způsobem (spolu s `const`), jak deklarovat proměnné.
diff --git a/1-js/06-advanced-functions/05-global-object/article.md b/1-js/06-advanced-functions/05-global-object/article.md
index cf4839d94..3d54593db 100644
--- a/1-js/06-advanced-functions/05-global-object/article.md
+++ b/1-js/06-advanced-functions/05-global-object/article.md
@@ -1,89 +1,89 @@
-# Global object
+# Globální objekt
-The global object provides variables and functions that are available anywhere. By default, those that are built into the language or the environment.
+Globální objekt poskytuje proměnné a funkce, které jsou dostupné všude. Standardně jsou to ty, které jsou vestavěny do jazyka nebo prostředí.
-In a browser it is named `window`, for Node.js it is `global`, for other environments it may have another name.
+V prohlížeči se jmenuje `window`, v Node.js je to `global`, v jiných prostředích může mít jiný název.
-Recently, `globalThis` was added to the language, as a standardized name for a global object, that should be supported across all environments. It's supported in all major browsers.
+Nedávno byl do jazyka přidán standardizovaný název globálního objektu `globalThis`, který by měla podporovat všechna prostředí. Všechny významné prohlížeče jej podporují.
-We'll use `window` here, assuming that our environment is a browser. If your script may run in other environments, it's better to use `globalThis` instead.
+Zde budeme používat `window`, jelikož předpokládáme, že naším prostředím je prohlížeč. Pokud váš skript má běžet v jiných prostředích, je lepší místo něj používat `globalThis`.
-All properties of the global object can be accessed directly:
+Ke všem vlastnostem globálního objektu lze přistupovat přímo:
```js run
-alert("Hello");
-// is the same as
-window.alert("Hello");
+alert("Ahoj");
+// je totéž jako
+window.alert("Ahoj");
```
-In a browser, global functions and variables declared with `var` (not `let/const`!) become the property of the global object:
+V prohlížeči se globální funkce a proměnné deklarované pomocí `var` (ne `let/const`!) stávají vlastnostmi globálního objektu:
```js run untrusted refresh
var gVar = 5;
-alert(window.gVar); // 5 (became a property of the global object)
+alert(window.gVar); // 5 (stala se vlastností globálního objektu)
```
-Function declarations have the same effect (statements with `function` keyword in the main code flow, not function expressions).
+Stejný efekt mají deklarace funkcí (příkazy s klíčovým slovem `function` v běhu hlavního kódu, ne funkční výrazy).
-Please don't rely on that! This behavior exists for compatibility reasons. Modern scripts use [JavaScript modules](info:modules) where such a thing doesn't happen.
+Prosíme, nespoléhejte se na to! Toto chování existuje z důvodů kompatibility. Moderní skripty používají [JavaScriptové moduly](info:modules), v nichž se takové věci nedějí.
-If we used `let` instead, such thing wouldn't happen:
+Kdybychom místo toho použili `let`, toto by se nestalo:
```js run untrusted refresh
let gLet = 5;
-alert(window.gLet); // undefined (doesn't become a property of the global object)
+alert(window.gLet); // undefined (nestala se vlastností globálního objektu)
```
-If a value is so important that you'd like to make it available globally, write it directly as a property:
+Je-li hodnota tak důležitá, že byste ji chtěli učinit globálně dostupnou, uveďte ji rovnou jako vlastnost:
```js run
*!*
-// make current user information global, to let all scripts access it
-window.currentUser = {
- name: "John"
+// učiní informaci o aktuálním uživateli globální, aby k ní mohly přistupovat všechny skripty
+window.aktuálníUživatel = {
+ jméno: "Jan"
};
*/!*
-// somewhere else in code
-alert(currentUser.name); // John
+// někde jinde v kódu
+alert(aktuálníUživatel.jméno); // Jan
-// or, if we have a local variable with the name "currentUser"
-// get it from window explicitly (safe!)
-alert(window.currentUser.name); // John
+// nebo, máme-li lokální proměnnou s názvem „aktuálníUživatel“,
+// načteme ji přímo z objektu window (bezpečně!)
+alert(window.aktuálníUživatel.jméno); // Jan
```
-That said, using global variables is generally discouraged. There should be as few global variables as possible. The code design where a function gets "input" variables and produces certain "outcome" is clearer, less prone to errors and easier to test than if it uses outer or global variables.
+Tím chceme říci, že používání globálních proměnných se obecně nedoporučuje. Mělo by jich být co nejméně. Návrh kódu, v němž funkce přijímá „vstupní“ proměnné a produkuje určitý „výstup“, je čistší, méně náchylný k chybám a snadnější na otestování, než když funkce používá vnější či globální proměnné.
-## Using for polyfills
+## Využití pro polyfilly
-We use the global object to test for support of modern language features.
+Globální objekt používáme k testování, zda jsou podporovány moderní vlastnosti jazyka.
-For instance, test if a built-in `Promise` object exists (it doesn't in really old browsers):
+Například otestujeme, zda existuje vestavěný objekt `Promise` (neexistuje v zastaralých prohlížečích):
```js run
if (!window.Promise) {
- alert("Your browser is really old!");
+ alert("Máte zastaralý prohlížeč!");
}
```
-If there's none (say, we're in an old browser), we can create "polyfills": add functions that are not supported by the environment, but exist in the modern standard.
+Pokud neexistuje (řekněme, že jsme ve starém prohlížeči), můžeme vytvořit „polyfilly“: přidáme funkce, které toto prostředí nepodporuje, ale v moderním standardu existují.
```js run
if (!window.Promise) {
- window.Promise = ... // custom implementation of the modern language feature
+ window.Promise = ... // vlastní implementace moderní vlastnosti jazyka
}
```
-## Summary
+## Shrnutí
-- The global object holds variables that should be available everywhere.
+- Globální objekt obsahuje proměnné, které by měly být dostupné odkudkoli.
- That includes JavaScript built-ins, such as `Array` and environment-specific values, such as `window.innerHeight` -- the window height in the browser.
-- The global object has a universal name `globalThis`.
+ Patří sem vestavěné prvky JavaScriptu, např. `Array`, a proměnné specifické pro určitá prostředí, např. `window.innerHeight` -- výška okna v prohlížeči.
+- Globální objekt má univerzální název `globalThis`.
- ...But more often is referred by "old-school" environment-specific names, such as `window` (browser) and `global` (Node.js).
-- We should store values in the global object only if they're truly global for our project. And keep their number at minimum.
-- In-browser, unless we're using [modules](info:modules), global functions and variables declared with `var` become a property of the global object.
-- To make our code future-proof and easier to understand, we should access properties of the global object directly, as `window.x`.
+ ...Častěji se na něj však odkazují názvy „ze staré školy“ specifické pro jednotlivá prostředí, např. `window` (prohlížeč) nebo `global` (Node.js).
+- Do globálního objektu bychom měli ukládat hodnoty jen tehdy, pokud jsou v našem projektu doopravdy globální, a udržovat jejich počet na minimu.
+- V prohlížeči, pokud nepoužíváme [moduly](info:modules), se globální funkce a proměnné deklarované pomocí `var` stávají vlastnostmi globálního objektu.
+- Aby náš kód zůstal do budoucna odolný a lépe srozumitelný, měli bychom přistupovat k vlastnostem globálního objektu přímo, např. `window.x`.
diff --git a/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/_js.view/solution.js b/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/_js.view/solution.js
index ce894698d..848d4b3c5 100644
--- a/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/_js.view/solution.js
+++ b/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/_js.view/solution.js
@@ -1,13 +1,13 @@
-function makeCounter() {
- let count = 0;
+function vytvořČítač() {
+ let počet = 0;
- function counter() {
- return count++;
+ function čítač() {
+ return počet++;
}
- counter.set = value => count = value;
+ čítač.nastav = hodnota => počet = hodnota;
- counter.decrease = () => count--;
+ čítač.sniž = () => počet--;
- return counter;
+ return čítač;
}
diff --git a/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/_js.view/source.js b/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/_js.view/source.js
index 5bf29aa2d..8b071b8bf 100644
--- a/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/_js.view/source.js
+++ b/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/_js.view/source.js
@@ -1,18 +1,18 @@
-function makeCounter() {
- let count = 0;
+function vytvořČítač() {
+ let počet = 0;
- // ... your code ...
+ // ... váš kód ...
}
-let counter = makeCounter();
+let čítač = vytvořČítač();
-alert( counter() ); // 0
-alert( counter() ); // 1
+alert( čítač() ); // 0
+alert( čítač() ); // 1
-counter.set(10); // set the new count
+čítač.nastav(10); // nastaví nový počet
-alert( counter() ); // 10
+alert( čítač() ); // 10
-counter.decrease(); // decrease the count by 1
+čítač.sniž(); // sníží počet o 1
-alert( counter() ); // 10 (instead of 11)
+alert( čítač() ); // 10 (místo 11)
diff --git a/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/_js.view/test.js b/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/_js.view/test.js
index 0e613aba7..02c5b30bc 100644
--- a/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/_js.view/test.js
+++ b/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/_js.view/test.js
@@ -1,39 +1,39 @@
-describe("counter", function() {
+describe("čítač", function() {
- it("increases from call to call", function() {
+ it("zvýší se při každém volání", function() {
- let counter = makeCounter();
+ let čítač = vytvořČítač();
- assert.equal( counter(), 0 );
- assert.equal( counter(), 1 );
- assert.equal( counter(), 2 );
+ assert.equal( čítač(), 0 );
+ assert.equal( čítač(), 1 );
+ assert.equal( čítač(), 2 );
});
- describe("counter.set", function() {
- it("sets the count", function() {
+ describe("čítač.nastav", function() {
+ it("nastaví počet", function() {
- let counter = makeCounter();
+ let čítač = vytvořČítač();
- counter.set(10);
+ čítač.nastav(10);
- assert.equal( counter(), 10 );
- assert.equal( counter(), 11 );
+ assert.equal( čítač(), 10 );
+ assert.equal( čítač(), 11 );
});
});
- describe("counter.decrease", function() {
- it("decreases the count", function() {
+ describe("čítač.sniž", function() {
+ it("sníží počet", function() {
- let counter = makeCounter();
+ let čítač = vytvořČítač();
- counter.set(10);
+ čítač.nastav(10);
- assert.equal( counter(), 10 );
+ assert.equal( čítač(), 10 );
- counter.decrease();
+ čítač.sniž();
- assert.equal( counter(), 10 );
+ assert.equal( čítač(), 10 );
});
});
diff --git a/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/solution.md b/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/solution.md
index e829d96ee..c2456431f 100644
--- a/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/solution.md
+++ b/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/solution.md
@@ -1,2 +1,2 @@
-The solution uses `count` in the local variable, but addition methods are written right into the `counter`. They share the same outer lexical environment and also can access the current `count`.
+Řešení využívá `počet` v lokální proměnné, ale přidané metody jsou vepsány přímo do funkce `čítač`. Sdílejí stejné vnější lexikální prostředí a mohou také přistupovat k aktuální hodnotě proměnné `počet`.
diff --git a/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/task.md b/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/task.md
index a11821d67..4479ff70f 100644
--- a/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/task.md
+++ b/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/task.md
@@ -2,14 +2,14 @@ importance: 5
---
-# Set and decrease for counter
+# Nastavení a snížení čítače
-Modify the code of `makeCounter()` so that the counter can also decrease and set the number:
+Upravte kód funkce `vytvořČítač()` tak, aby tento čítač uměl také snížit a nastavit svou hodnotu:
-- `counter()` should return the next number (as before).
-- `counter.set(value)` should set the counter to `value`.
-- `counter.decrease()` should decrease the counter by 1.
+- `čítač()` by měl vracet další číslo (jako dříve).
+- `čítač.nastav(hodnota)` by měl nastavit čítač na hodnotu `hodnota`.
+- `čítač.sniž()` by měl snížit čítač o 1.
-See the sandbox code for the complete usage example.
+Úplný příklad použití uvidíte na kódu z pískoviště.
-P.S. You can use either a closure or the function property to keep the current count. Or write both variants.
+P.S. K uchovávání aktuálního počtu můžete využívat buď uzávěr, nebo vlastnost funkce. Nebo napsat obě varianty.
diff --git a/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/_js.view/solution.js b/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/_js.view/solution.js
index c7d7d734e..3fd3f67c9 100644
--- a/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/_js.view/solution.js
+++ b/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/_js.view/solution.js
@@ -1,14 +1,14 @@
-function sum(a) {
+function sečti(a) {
- let currentSum = a;
+ let aktuálníSoučet = a;
function f(b) {
- currentSum += b;
+ aktuálníSoučet += b;
return f;
}
f.toString = function() {
- return currentSum;
+ return aktuálníSoučet;
};
return f;
diff --git a/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/_js.view/source.js b/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/_js.view/source.js
index f10dca5dc..e22e81757 100644
--- a/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/_js.view/source.js
+++ b/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/_js.view/source.js
@@ -1,12 +1,12 @@
-function sum(a){
- // Your code goes here.
+function sečti(a){
+ // Sem přijde váš kód.
}
/*
-sum(1)(2) == 3; // 1 + 2
-sum(1)(2)(3) == 6; // 1 + 2 + 3
-sum(5)(-1)(2) == 6
-sum(6)(-1)(-2)(-3) == 0
-sum(0)(1)(2)(3)(4)(5) == 15
+sečti(1)(2) == 3; // 1 + 2
+sečti(1)(2)(3) == 6; // 1 + 2 + 3
+sečti(5)(-1)(2) == 6
+sečti(6)(-1)(-2)(-3) == 0
+sečti(0)(1)(2)(3)(4)(5) == 15
*/
diff --git a/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/_js.view/test.js b/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/_js.view/test.js
index ed567d330..5e988aaa4 100644
--- a/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/_js.view/test.js
+++ b/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/_js.view/test.js
@@ -1,19 +1,19 @@
-describe("sum", function(){
+describe("sečti", function(){
- it("sum(1)(2) == 3", function(){
- assert.equal(3, sum(1)(2));
+ it("sečti(1)(2) == 3", function(){
+ assert.equal(3, sečti(1)(2));
});
- it("sum(5)(-1)(2) == 6", function(){
- assert.equal(6, sum(5)(-1)(2));
+ it("sečti(5)(-1)(2) == 6", function(){
+ assert.equal(6, sečti(5)(-1)(2));
});
- it("sum(6)(-1)(-2)(-3) == 0", function(){
- assert.equal(0, sum(6)(-1)(-2)(-3));
+ it("sečti(6)(-1)(-2)(-3) == 0", function(){
+ assert.equal(0, sečti(6)(-1)(-2)(-3));
});
- it("sum(0)(1)(2)(3)(4)(5) == 15", function(){
- assert.equal(15, sum(0)(1)(2)(3)(4)(5));
+ it("sečti(0)(1)(2)(3)(4)(5) == 15", function(){
+ assert.equal(15, sečti(0)(1)(2)(3)(4)(5));
});
});
diff --git a/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/solution.md b/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/solution.md
index e97039f72..ec9fbcc47 100644
--- a/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/solution.md
+++ b/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/solution.md
@@ -1,55 +1,55 @@
-1. For the whole thing to work *anyhow*, the result of `sum` must be function.
-2. That function must keep in memory the current value between calls.
-3. According to the task, the function must become the number when used in `==`. Functions are objects, so the conversion happens as described in the chapter , and we can provide our own method that returns the number.
+1. Aby to celé *jakkoli* fungovalo, výsledek funkce `sečti` musí být funkce.
+2. Tato funkce si musí udržovat v paměti aktuální hodnotu mezi voláními.
+3. Podle zadání se funkce musí stát číslem, když je použita v `==`. Funkce jsou objekty, takže konverze se odehrává tak, jak je popsáno v kapitole , a my můžeme poskytnout svou vlastní metodu, která toto číslo vrátí.
-Now the code:
+Nyní kód:
```js demo run
-function sum(a) {
+function sečti(a) {
- let currentSum = a;
+ let aktuálníSoučet = a;
function f(b) {
- currentSum += b;
+ aktuálníSoučet += b;
return f;
}
f.toString = function() {
- return currentSum;
+ return aktuálníSoučet;
};
return f;
}
-alert( sum(1)(2) ); // 3
-alert( sum(5)(-1)(2) ); // 6
-alert( sum(6)(-1)(-2)(-3) ); // 0
-alert( sum(0)(1)(2)(3)(4)(5) ); // 15
+alert( sečti(1)(2) ); // 3
+alert( sečti(5)(-1)(2) ); // 6
+alert( sečti(6)(-1)(-2)(-3) ); // 0
+alert( sečti(0)(1)(2)(3)(4)(5) ); // 15
```
-Please note that the `sum` function actually works only once. It returns function `f`.
+Prosíme všimněte si, že funkce `sečti` se ve skutečnosti spustí jenom jednou. Vrátí funkci `f`.
-Then, on each subsequent call, `f` adds its parameter to the sum `currentSum`, and returns itself.
+Pak funkce `f` při každém následném volání přičte svůj parametr k součtu `aktuálníSoučet` a vrátí sebe sama.
-**There is no recursion in the last line of `f`.**
+**Na posledním řádku funkce `f` není rekurze.**
-Here is what recursion looks like:
+Rekurze by vypadala takto:
```js
function f(b) {
- currentSum += b;
- return f(); // <-- recursive call
+ aktuálníSoučet += b;
+ return f(); // <-- rekurzívní volání
}
```
-And in our case, we just return the function, without calling it:
+V našem případě vracíme jen funkci, aniž bychom ji volali:
```js
function f(b) {
- currentSum += b;
- return f; // <-- does not call itself, returns itself
+ aktuálníSoučet += b;
+ return f; // <-- nevolá sama sebe, vrací sama sebe
}
```
-This `f` will be used in the next call, again return itself, as many times as needed. Then, when used as a number or a string -- the `toString` returns the `currentSum`. We could also use `Symbol.toPrimitive` or `valueOf` here for the conversion.
+Tato funkce `f` bude použita při dalším volání a opět vrátí sebe sama, tolikrát, kolikrát je zapotřebí. Když ji pak použijeme jako číslo nebo řetězec, `toString` vrátí `aktuálníSoučet`. Zde bychom pro konverzi mohli také použít `Symbol.toPrimitive` nebo `valueOf`.
diff --git a/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/task.md b/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/task.md
index dc13f260b..aad266a59 100644
--- a/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/task.md
+++ b/1-js/06-advanced-functions/06-function-object/5-sum-many-brackets/task.md
@@ -2,16 +2,16 @@ importance: 2
---
-# Sum with an arbitrary amount of brackets
+# Sčítání s libovolným počtem závorek
-Write function `sum` that would work like this:
+Napište funkci `sečti`, která bude fungovat takto:
```js
-sum(1)(2) == 3; // 1 + 2
-sum(1)(2)(3) == 6; // 1 + 2 + 3
-sum(5)(-1)(2) == 6
-sum(6)(-1)(-2)(-3) == 0
-sum(0)(1)(2)(3)(4)(5) == 15
+sečti(1)(2) == 3; // 1 + 2
+sečti(1)(2)(3) == 6; // 1 + 2 + 3
+sečti(5)(-1)(2) == 6
+sečti(6)(-1)(-2)(-3) == 0
+sečti(0)(1)(2)(3)(4)(5) == 15
```
-P.S. Hint: you may need to setup custom object to primitive conversion for your function.
\ No newline at end of file
+P.S. Rada: možná budete pro svou funkci potřebovat nastavit vlastní konverzi objektu na primitiv.
\ No newline at end of file
diff --git a/1-js/06-advanced-functions/06-function-object/article.md b/1-js/06-advanced-functions/06-function-object/article.md
index 8419ae763..68749baf6 100644
--- a/1-js/06-advanced-functions/06-function-object/article.md
+++ b/1-js/06-advanced-functions/06-function-object/article.md
@@ -1,353 +1,351 @@
-# Function object, NFE
+# Funkční objekt, NFE
-As we already know, a function in JavaScript is a value.
+Jak již víme, funkce v JavaScriptu je hodnota.
-Every value in JavaScript has a type. What type is a function?
+Každá hodnota v JavaScriptu má svůj typ. Jakého typu je funkce?
-In JavaScript, functions are objects.
+V JavaScriptu jsou funkce objekty.
-A good way to imagine functions is as callable "action objects". We can not only call them, but also treat them as objects: add/remove properties, pass by reference etc.
+Dobrý způsob, jak si představit funkce, je představit si je jako „akční objekty“, které lze volat. Můžeme je nejenom volat, ale i zacházet s nimi jako s objekty: přidávat a ubírat vlastnosti, předávat je odkazem a tak dále.
-## The "name" property
+## Vlastnost „name“
-Function objects contain some useable properties.
+Funkční objekty obsahují některé užitečné vlastnosti.
-For instance, a function's name is accessible as the "name" property:
+Například název funkce je dostupný ve vlastnosti `name`:
```js run
-function sayHi() {
- alert("Hi");
+function řekniAhoj() {
+ alert("Ahoj");
}
-alert(sayHi.name); // sayHi
+alert(řekniAhoj.name); // řekniAhoj
```
-What's kind of funny, the name-assigning logic is smart. It also assigns the correct name to a function even if it's created without one, and then immediately assigned:
+Zábavné je, že logika přiřazení názvu je chytrá a přiřadí korektní název i funkci, která je vytvořena bez názvu a pak okamžitě přiřazena:
```js run
-let sayHi = function() {
- alert("Hi");
+let řekniAhoj = function() {
+ alert("Ahoj");
};
-alert(sayHi.name); // sayHi (there's a name!)
+alert(řekniAhoj.name); // řekniAhoj (je tady název!)
```
-It also works if the assignment is done via a default value:
+Funguje to i tehdy, je-li přiřazena jako standardní hodnota:
```js run
-function f(sayHi = function() {}) {
- alert(sayHi.name); // sayHi (works!)
+function f(řekniAhoj = function() {}) {
+ alert(řekniAhoj.name); // řekniAhoj (funguje!)
}
f();
```
-In the specification, this feature is called a "contextual name". If the function does not provide one, then in an assignment it is figured out from the context.
+Ve specifikaci se tato vlastnost nazývá „kontextuální název“ („contextual name“). Jestliže funkce neobsahuje vlastní název, je při přiřazení detekován z kontextu.
-Object methods have names too:
+I metody objektů mají názvy:
```js run
-let user = {
+let uživatel = {
- sayHi() {
+ řekniAhoj() {
// ...
},
- sayBye: function() {
+ řekniNashle: function() {
// ...
}
}
-alert(user.sayHi.name); // sayHi
-alert(user.sayBye.name); // sayBye
+alert(uživatel.řekniAhoj.name); // řekniAhoj
+alert(uživatel.řekniNashle.name); // řekniNashle
```
-There's no magic though. There are cases when there's no way to figure out the right name. In that case, the name property is empty, like here:
+Není v tom ovšem nic magického. Existují případy, kdy není způsob, jak zjistit skutečný název. V takovém případě je vlastnost `name` prázdná, například zde:
```js run
-// function created inside array
-let arr = [function() {}];
+// funkce vytvořená uvnitř pole
+let pole = [function() {}];
-alert( arr[0].name ); //
-// the engine has no way to set up the right name, so there is none
+alert( pole[0].name ); //
+// motor nemá jak zjistit správný název, takže tady žádný není
```
-In practice, however, most functions do have a name.
+V praxi však většina funkcí název má.
-## The "length" property
+## Vlastnost „length“
-There is another built-in property "length" that returns the number of function parameters, for instance:
+Další vestavěná vlastnost je `length`, která vrací počet parametrů funkce, například:
```js run
function f1(a) {}
function f2(a, b) {}
-function many(a, b, ...more) {}
+function mnoho(a, b, ...další) {}
alert(f1.length); // 1
alert(f2.length); // 2
-alert(many.length); // 2
+alert(mnoho.length); // 2
```
-Here we can see that rest parameters are not counted.
+Zde vidíme, že zbytkové parametry se nepočítají.
-The `length` property is sometimes used for [introspection](https://en.wikipedia.org/wiki/Type_introspection) in functions that operate on other functions.
+Vlastnost `length` se někdy používá pro [introspekci](https://en.wikipedia.org/wiki/Type_introspection) ve funkcích, které operují s jinými funkcemi.
-For instance, in the code below the `ask` function accepts a `question` to ask and an arbitrary number of `handler` functions to call.
+Například v níže uvedeném kódu funkce `zeptejSe` přijímá parametr `otázka`, kterou položí, a libovolný počet funkčních handlerů v parametru `handlery`, které zavolá.
-Once a user provides their answer, the function calls the handlers. We can pass two kinds of handlers:
+Jakmile uživatel poskytne odpověď, funkce zavolá handlery. Můžeme předávat dva druhy handlerů:
-- A zero-argument function, which is only called when the user gives a positive answer.
-- A function with arguments, which is called in either case and returns an answer.
+- Funkci bez argumentů, která se volá jedině tehdy, když uživatel zadá kladnou odpověď.
+- Funkci s argumenty, která se volá v každém případě a vrátí nějakou odpověď.
-To call `handler` the right way, we examine the `handler.length` property.
+Abychom zavolali `handler` správně, prozkoumáme vlastnost `handler.length`.
-The idea is that we have a simple, no-arguments handler syntax for positive cases (most frequent variant), but are able to support universal handlers as well:
+Myšlenkou je, že máme jednoduchou syntaxi handleru bez argumentů pro kladné případy (nejčastější varianta), ale jsme schopni podporovat i univerzální handlery:
```js run
-function ask(question, ...handlers) {
- let isYes = confirm(question);
+function zeptejSe(otázka, ...handlery) {
+ let jeAno = confirm(otázka);
- for(let handler of handlers) {
+ for(let handler of handlery) {
if (handler.length == 0) {
- if (isYes) handler();
+ if (jeAno) handler();
} else {
- handler(isYes);
+ handler(jeAno);
}
}
}
-// for positive answer, both handlers are called
-// for negative answer, only the second one
-ask("Question?", () => alert('You said yes'), result => alert(result));
+// při kladné odpovědi se volají oba handlery
+// při záporné odpovědi se volá jen druhý
+zeptejSe("Otázka?", () => alert('Řekl jste ano'), výsledek => alert(výsledek));
```
-This is a particular case of so-called [polymorphism](https://en.wikipedia.org/wiki/Polymorphism_(computer_science)) -- treating arguments differently depending on their type or, in our case depending on the `length`. The idea does have a use in JavaScript libraries.
+Toto je zvláštní případ tzv. [polymorfismu](https://cs.wikipedia.org/wiki/Polymorfismus_(programování)) -- odlišného zacházení s argumenty v závislosti na jejich typu nebo v našem případě v závislosti na jejich počtu v `length`. Tato myšlenka je často využívána v knihovnách JavaScriptu.
-## Custom properties
+## Vlastní vlastnosti
-We can also add properties of our own.
+Můžeme si také přidávat svoje vlastní vlastnosti.
-Here we add the `counter` property to track the total calls count:
+Zde přidáme vlastnost `čítač`, která počítá celkový počet volání:
```js run
-function sayHi() {
- alert("Hi");
+function řekniAhoj() {
+ alert("Ahoj");
*!*
- // let's count how many times we run
- sayHi.counter++;
+ // spočítáme, kolikrát jsme tuto funkci volali
+ řekniAhoj.čítač++;
*/!*
}
-sayHi.counter = 0; // initial value
+řekniAhoj.čítač = 0; // počáteční hodnota
-sayHi(); // Hi
-sayHi(); // Hi
+řekniAhoj(); // Ahoj
+řekniAhoj(); // Ahoj
-alert( `Called ${sayHi.counter} times` ); // Called 2 times
+alert( `Voláno ${řekniAhoj.čítač}krát` ); // Voláno 2krát
```
-```warn header="A property is not a variable"
-A property assigned to a function like `sayHi.counter = 0` does *not* define a local variable `counter` inside it. In other words, a property `counter` and a variable `let counter` are two unrelated things.
+```warn header="Vlastnost není proměnná"
+Vlastnost přiřazená funkci, např. `řekniAhoj.čítač = 0`, *nedefinuje* uvnitř funkce lokální proměnnou `čítač`. Jinými slovy, vlastnost `čítač` a proměnná `let čítač` jsou dvě různé věci.
-We can treat a function as an object, store properties in it, but that has no effect on its execution. Variables are not function properties and vice versa. These are just parallel worlds.
+Můžeme s funkcí zacházet jako s objektem, ukládat do ní vlastnosti, ale to nemá žádný vliv na její provádění. Proměnné nejsou vlastnosti funkce a naopak. Jsou to dva paralelní světy.
```
-Function properties can replace closures sometimes. For instance, we can rewrite the counter function example from the chapter to use a function property:
+Vlastnosti funkce někdy mohou nahradit uzávěry. Například můžeme přepsat příklad funkce čítače z kapitoly tak, že použijeme vlastnost funkce:
```js run
-function makeCounter() {
- // instead of:
- // let count = 0
+function vytvořČítač() {
+ // namísto:
+ // let počet = 0
- function counter() {
- return counter.count++;
+ function čítač() {
+ return čítač.počet++;
};
- counter.count = 0;
+ čítač.počet = 0;
- return counter;
+ return čítač;
}
-let counter = makeCounter();
-alert( counter() ); // 0
-alert( counter() ); // 1
+let čítač = vytvořČítač();
+alert( čítač() ); // 0
+alert( čítač() ); // 1
```
-The `count` is now stored in the function directly, not in its outer Lexical Environment.
+Nyní je `počet` uložen přímo ve funkci, ne v jejím vnějším lexikálním prostředí.
-Is it better or worse than using a closure?
+Je to lepší nebo horší, než použít uzávěr?
-The main difference is that if the value of `count` lives in an outer variable, then external code is unable to access it. Only nested functions may modify it. And if it's bound to a function, then such a thing is possible:
+Hlavním rozdílem je, že jestliže hodnota `počet` přebývá ve vnější proměnné, externí kód není schopen k ní přistupovat. Mohou ji modifikovat jedině vnořené funkce. Ale jestliže je vázána na funkci, pak je něco takového možné:
```js run
-function makeCounter() {
+function vytvořČítač() {
- function counter() {
- return counter.count++;
+ function čítač() {
+ return čítač.počet++;
};
- counter.count = 0;
+ čítač.počet = 0;
- return counter;
+ return čítač;
}
-let counter = makeCounter();
+let čítač = vytvořČítač();
*!*
-counter.count = 10;
-alert( counter() ); // 10
+čítač.počet = 10;
+alert( čítač() ); // 10
*/!*
```
-So the choice of implementation depends on our aims.
+Volba implementace tedy závisí na našich potřebách.
-## Named Function Expression
+## Pojmenovaný funkční výraz
-Named Function Expression, or NFE, is a term for Function Expressions that have a name.
+Pojmenovaný funkční výraz („Named Function Expression“), zkráceně NFE, je termín označující funkční výraz, který má nějaký název.
-For instance, let's take an ordinary Function Expression:
+Vezměme si například obyčejný funkční výraz:
```js
-let sayHi = function(who) {
- alert(`Hello, ${who}`);
+let řekniAhoj = function(kdo) {
+ alert(`Ahoj, ${kdo}`);
};
```
-And add a name to it:
+A přidejme mu název:
```js
-let sayHi = function *!*func*/!*(who) {
- alert(`Hello, ${who}`);
+let řekniAhoj = function *!*funkce*/!*(kdo) {
+ alert(`Ahoj, ${kdo}`);
};
```
-Did we achieve anything here? What's the purpose of that additional `"func"` name?
+Dosáhli jsme tím něčeho? Jaký je smysl přidaného názvu `„funkce“`?
-First let's note, that we still have a Function Expression. Adding the name `"func"` after `function` did not make it a Function Declaration, because it is still created as a part of an assignment expression.
+Nejprve si všimněme, že stále máme funkční výraz. Přidání názvu `„funkce“` za `function` z něj neučinilo deklaraci funkce, protože funkce je stále vytvořena jako součást přiřazovacího výrazu.
-Adding such a name also did not break anything.
+Přidání takového názvu rovněž nic nerozbilo.
-The function is still available as `sayHi()`:
+Funkce je stále dostupná jako `řekniAhoj()`:
```js run
-let sayHi = function *!*func*/!*(who) {
- alert(`Hello, ${who}`);
+let řekniAhoj = function *!*funkce*/!*(kdo) {
+ alert(`Ahoj, ${kdo}`);
};
-sayHi("John"); // Hello, John
+řekniAhoj("Jan"); // Ahoj, Jan
```
-There are two special things about the name `func`, that are the reasons for it:
+Název `funkce` má dvě speciální věci, které jsou důvodem pro jeho použití:
-1. It allows the function to reference itself internally.
-2. It is not visible outside of the function.
+1. Název umožňuje funkci odkazovat se uvnitř sebe na sebe sama.
+2. Název není viditelný zvnějšku funkce.
-For instance, the function `sayHi` below calls itself again with `"Guest"` if no `who` is provided:
+Například následující funkce `řekniAhoj` volá sama sebe s parametrem `"Host"`, není-li předáno `kdo`:
```js run
-let sayHi = function *!*func*/!*(who) {
- if (who) {
- alert(`Hello, ${who}`);
+let řekniAhoj = function *!*funkce*/!*(kdo) {
+ if (kdo) {
+ alert(`Ahoj, ${kdo}`);
} else {
*!*
- func("Guest"); // use func to re-call itself
+ funkce("Host"); // použijeme „funkce“ k volání sebe sama
*/!*
}
};
-sayHi(); // Hello, Guest
+řekniAhoj(); // Ahoj, Host
-// But this won't work:
-func(); // Error, func is not defined (not visible outside of the function)
+// Ale tohle nebude fungovat:
+funkce(); // Chyba, funkce není definována (není viditelná zvnějšku funkce)
```
-Why do we use `func`? Maybe just use `sayHi` for the nested call?
+Proč používáme `funkce`? Možná by pro vnořené volání stačilo použít `řekniAhoj`?
-
-Actually, in most cases we can:
+Ve skutečnosti ve většině případů ano:
```js
-let sayHi = function(who) {
- if (who) {
- alert(`Hello, ${who}`);
+let řekniAhoj = function(kdo) {
+ if (kdo) {
+ alert(`Ahoj, ${kdo}`);
} else {
*!*
- sayHi("Guest");
+ řekniAhoj("Host");
*/!*
}
};
```
-The problem with that code is that `sayHi` may change in the outer code. If the function gets assigned to another variable instead, the code will start to give errors:
+Problém s tímto kódem je, že `řekniAhoj` se může ve vnějším kódu změnit. Jestliže funkce bude přiřazena do jiné proměnné, tento kód začne způsobovat chyby:
```js run
-let sayHi = function(who) {
- if (who) {
- alert(`Hello, ${who}`);
+let řekniAhoj = function(kdo) {
+ if (kdo) {
+ alert(`Ahoj, ${kdo}`);
} else {
*!*
- sayHi("Guest"); // Error: sayHi is not a function
+ řekniAhoj("Host"); // Chyba: řekniAhoj není funkce
*/!*
}
};
-let welcome = sayHi;
-sayHi = null;
+let vítej = řekniAhoj;
+řekniAhoj = null;
-welcome(); // Error, the nested sayHi call doesn't work any more!
+vítej(); // Chyba, vnořené volání řekniAhoj už nefunguje!
```
-That happens because the function takes `sayHi` from its outer lexical environment. There's no local `sayHi`, so the outer variable is used. And at the moment of the call that outer `sayHi` is `null`.
+To se stane proto, že funkce přebírá `řekniAhoj` ze svého vnějšího lexikálního prostředí. Neexistuje lokální `řekniAhoj`, takže se použije vnější proměnná. A v okamžiku volání je vnější `řekniAhoj` rovno `null`.
-The optional name which we can put into the Function Expression is meant to solve exactly these kinds of problems.
+Nepovinný název, který můžeme vložit do funkčního výrazu, je určen právě k řešení problémů tohoto druhu.
-Let's use it to fix our code:
+Použijme jej k opravě našeho kódu:
```js run
-let sayHi = function *!*func*/!*(who) {
- if (who) {
- alert(`Hello, ${who}`);
+let řekniAhoj = function *!*funkce*/!*(kdo) {
+ if (kdo) {
+ alert(`Ahoj, ${kdo}`);
} else {
*!*
- func("Guest"); // Now all fine
+ funkce("Host"); // Nyní je vše v pořádku
*/!*
}
};
-let welcome = sayHi;
-sayHi = null;
+let vítej = řekniAhoj;
+řekniAhoj = null;
-welcome(); // Hello, Guest (nested call works)
+vítej(); // Ahoj, Host (vnořené volání funguje)
```
-Now it works, because the name `"func"` is function-local. It is not taken from outside (and not visible there). The specification guarantees that it will always reference the current function.
+Nyní to funguje, protože název `„funkce“` je funkčně lokální. Nepřebírá se zvnějšku (a není tam viditelný). Specifikace zaručuje, že se bude vždy odkazovat na aktuální funkci.
-The outer code still has its variable `sayHi` or `welcome`. And `func` is an "internal function name", the way for the function to call itself reliably.
+Vnější kód stále má svou proměnnou `řekniAhoj` nebo `vítej`. A `funkce` je „interní funkční název“, způsob, jakým tato funkce může spolehlivě volat sama sebe.
-```smart header="There's no such thing for Function Declaration"
-The "internal name" feature described here is only available for Function Expressions, not for Function Declarations. For Function Declarations, there is no syntax for adding an "internal" name.
+```smart header="Pro deklarace funkce nic takového neexistuje"
+Popsaná vlastnost „interní název“ je k dispozici jen pro funkční výrazy, ne pro deklarace funkcí. V deklaracích funkcí neexistuje žádná syntaxe, jak přidat „interní“ název.
-Sometimes, when we need a reliable internal name, it's the reason to rewrite a Function Declaration to Named Function Expression form.
+Někdy, když potřebujeme spolehlivý interní název, je to důvod, proč přepsat deklaraci funkce do formy pojmenovaného funkčního výrazu.
```
-## Summary
-
-Functions are objects.
+## Shrnutí
-Here we covered their properties:
+Funkce jsou objekty.
-- `name` -- the function name. Usually taken from the function definition, but if there's none, JavaScript tries to guess it from the context (e.g. an assignment).
-- `length` -- the number of arguments in the function definition. Rest parameters are not counted.
+Zde jsme probrali jejich vlastnosti:
-If the function is declared as a Function Expression (not in the main code flow), and it carries the name, then it is called a Named Function Expression. The name can be used inside to reference itself, for recursive calls or such.
+- `name` -- název funkce. Obvykle se přebírá z definice funkce, ale pokud tam není, JavaScript se pokusí odhadnout jej z kontextu (tj. z přiřazení).
+- `length` -- počet argumentů v definici funkce. Zbytkové parametry se nepočítají.
-Also, functions may carry additional properties. Many well-known JavaScript libraries make great use of this feature.
+Je-li funkce deklarována jako funkční výraz (ne v hlavním běhu kódu) a ten obsahuje název, nazývá se pojmenovaný funkční výraz. Název lze používat uvnitř funkce, aby se na ni odkazoval, pro rekurzívní volání a podobně.
-They create a "main" function and attach many other "helper" functions to it. For instance, the [jQuery](https://jquery.com) library creates a function named `$`. The [lodash](https://lodash.com) library creates a function `_`, and then adds `_.clone`, `_.keyBy` and other properties to it (see the [docs](https://lodash.com/docs) when you want to learn more about them). Actually, they do it to lessen their pollution of the global space, so that a single library gives only one global variable. That reduces the possibility of naming conflicts.
+Funkce si také může uchovávat přidané vlastnosti. Tuto vlastnost zhusta využívá mnoho dobře známých JavaScriptových knihoven.
+Vytvářejí „hlavní“ funkci a přidávají k ní mnoho dalších „pomocných“ funkcí. Například knihovna [jQuery](https://jquery.com) vytváří funkci jménem `$`. Knihovna [lodash](https://lodash.com) vytváří funkci jménem `_` a pak do ní přidává `_.clone`, `_.keyBy` a jiné vlastnosti (pokud se o nich chcete dozvědět víc, nahlédněte do [dokumentace](https://lodash.com/docs)). Ve skutečnosti to dělají proto, aby snížily zamoření globálního prostoru, takže jedna knihovna vytváří pouze jednu globální proměnnou. Tím se snižuje pravděpodobnost konfliktů názvů.
-So, a function can do a useful job by itself and also carry a bunch of other functionality in properties.
+Funkce tedy může sama o sobě odvádět užitečnou práci a může také obsahovat hromadu jiných funkcionalit ve svých vlastnostech.
diff --git a/1-js/06-advanced-functions/07-new-function/article.md b/1-js/06-advanced-functions/07-new-function/article.md
index ffe264a4e..cfeb3ff05 100644
--- a/1-js/06-advanced-functions/07-new-function/article.md
+++ b/1-js/06-advanced-functions/07-new-function/article.md
@@ -1,123 +1,123 @@
-# The "new Function" syntax
+# Syntaxe „new Function“
-There's one more way to create a function. It's rarely used, but sometimes there's no alternative.
+Existuje ještě jeden způsob, jak vytvořit funkci. Používá se jen zřídka, ale někdy nemáme jinou možnost.
-## Syntax
+## Syntaxe
-The syntax for creating a function:
+Syntaxe vytvoření funkce:
```js
-let func = new Function ([arg1, arg2, ...argN], functionBody);
+let funkce = new Function ([arg1, arg2, ...argN], těloFunkce);
```
-The function is created with the arguments `arg1...argN` and the given `functionBody`.
+Funkce je vytvořena s argumenty `arg1...argN` a zadaným tělem `těloFunkce`.
-It's easier to understand by looking at an example. Here's a function with two arguments:
+Je snadnější tomu porozumět, když se podíváme na příklad. Toto je funkce se dvěma argumenty:
```js run
-let sum = new Function('a', 'b', 'return a + b');
+let sečti = new Function('a', 'b', 'return a + b');
-alert( sum(1, 2) ); // 3
+alert( sečti(1, 2) ); // 3
```
-And here there's a function without arguments, with only the function body:
+A zde je funkce bez argumentů, jenom s tělem:
```js run
-let sayHi = new Function('alert("Hello")');
+let řekniAhoj = new Function('alert("Ahoj")');
-sayHi(); // Hello
+řekniAhoj(); // Ahoj
```
-The major difference from other ways we've seen is that the function is created literally from a string, that is passed at run time.
+Hlavní rozdíl oproti ostatním způsobům, jaké jsme viděli, je, že funkce je vytvořena doslovně z řetězce, který je předán za běhu skriptu.
-All previous declarations required us, programmers, to write the function code in the script.
+Všechny předchozí deklarace po nás programátorech požadovaly, abychom zapsali kód funkce do skriptu.
-But `new Function` allows to turn any string into a function. For example, we can receive a new function from a server and then execute it:
+Avšak `new Function` umožňuje převést libovolný řetězec na funkci. Například můžeme získat novou funkci ze serveru a pak ji spustit:
```js
-let str = ... receive the code from a server dynamically ...
+let řetězec = ... dynamické získání kódu ze serveru ...
-let func = new Function(str);
-func();
+let funkce = new Function(řetězec);
+funkce();
```
-It is used in very specific cases, like when we receive code from a server, or to dynamically compile a function from a template, in complex web-applications.
+Používá se jen ve velmi specifických případech, například když získáme kód ze serveru, nebo když chceme dynamicky kompilovat funkci ze šablony ve složitých webových aplikacích.
-## Closure
+## Uzávěr
-Usually, a function remembers where it was born in the special property `[[Environment]]`. It references the Lexical Environment from where it's created (we covered that in the chapter ).
+Funkce si zpravidla pamatuje, kde se zrodila, ve speciální vlastnosti `[[Environment]]`. Ta se odkazuje na lexikální prostředí, z něhož byla funkce vytvořena (probrali jsme to v kapitole ).
-But when a function is created using `new Function`, its `[[Environment]]` is set to reference not the current Lexical Environment, but the global one.
+Když je však funkce vytvořena pomocí `new Function`, její vlastnost `[[Environment]]` se nenastaví na odkaz na aktuální lexikální prostředí, ale na globální.
-So, such function doesn't have access to outer variables, only to the global ones.
+Taková funkce tedy nemá přístup k vnějším proměnným, jedině ke globálním.
```js run
-function getFunc() {
- let value = "test";
+function vraťFunkci() {
+ let hodnota = "test";
*!*
- let func = new Function('alert(value)');
+ let funkce = new Function('alert(hodnota)');
*/!*
- return func;
+ return funkce;
}
-getFunc()(); // error: value is not defined
+vraťFunkci()(); // chyba: hodnota není definována
```
-Compare it with the regular behavior:
+Porovnejte si to s běžným chováním:
```js run
-function getFunc() {
- let value = "test";
+function vraťFunkci() {
+ let hodnota = "test";
*!*
- let func = function() { alert(value); };
+ let funkce = function() { alert(hodnota); };
*/!*
- return func;
+ return funkce;
}
-getFunc()(); // *!*"test"*/!*, from the Lexical Environment of getFunc
+vraťFunkci()(); // *!*"test"*/!*, z lexikálního prostředí funkce vraťFunkci
```
-This special feature of `new Function` looks strange, but appears very useful in practice.
+Tato speciální vlastnost `new Function` vypadá zvláštně, ale v praxi se ukazuje být velmi užitečná.
-Imagine that we must create a function from a string. The code of that function is not known at the time of writing the script (that's why we don't use regular functions), but will be known in the process of execution. We may receive it from the server or from another source.
+Představme si, že musíme vytvořit funkci z řetězce. Kód této funkce není znám v době psaní skriptu (to je důvod, proč nepoužijeme obvyklou funkci), ale bude znám při jeho běhu. Můžeme jej získat ze serveru nebo z jiného zdroje.
-Our new function needs to interact with the main script.
+Naše nová funkce musí interagovat s hlavním skriptem.
-What if it could access the outer variables?
+Co kdyby mohla přistupovat k vnějším proměnným?
-The problem is that before JavaScript is published to production, it's compressed using a *minifier* -- a special program that shrinks code by removing extra comments, spaces and -- what's important, renames local variables into shorter ones.
+Problém je v tom, že předtím, než je JavaScriptový skript zveřejněn k používání, je zkomprimován *minifikátorem* -- speciálním programem, který zkrátí kód tím, že odstraní komentáře, přebytečné mezery a -- co je důležité, přejmenuje názvy lokálních proměnných na kratší.
-For instance, if a function has `let userName`, minifier replaces it with `let a` (or another letter if this one is occupied), and does it everywhere. That's usually a safe thing to do, because the variable is local, nothing outside the function can access it. And inside the function, minifier replaces every mention of it. Minifiers are smart, they analyze the code structure, so they don't break anything. They're not just a dumb find-and-replace.
+Například jestliže funkce obsahuje `let uživatelskéJméno`, minifikátor je nahradí za `let a` (nebo jiné písmeno, které ještě není použito) a učiní tak všude. To je obvykle bezpečné, jelikož proměnná je lokální a nic mimo funkci k ní nemůže přistupovat. A uvnitř funkce minifikátor nahradí tuto proměnnou všude, kde je uvedena. Minifikátory jsou chytré, analyzují strukturu kódu, takže nic nerozbíjejí. Není to jen tupé najdi a nahraď.
-So if `new Function` had access to outer variables, it would be unable to find renamed `userName`.
+Kdyby tedy `new Function` měla přístup k vnějším proměnným, nedokázala by najít přejmenované `uživatelskéJméno`.
-**If `new Function` had access to outer variables, it would have problems with minifiers.**
+**Kdyby `new Function` měla přístup k vnějším proměnným, měla by problémy s minifikátory.**
-Besides, such code would be architecturally bad and prone to errors.
+Navíc by takový kód byl architektonicky špatný a náchylný k chybám.
-To pass something to a function, created as `new Function`, we should use its arguments.
+K tomu, abychom něco předali funkci vytvořené pomocí `new Function`, bychom měli používat její argumenty.
-## Summary
+## Shrnutí
-The syntax:
+Syntaxe:
```js
-let func = new Function ([arg1, arg2, ...argN], functionBody);
+let funkce = new Function ([arg1, arg2, ...argN], těloFunkce);
```
-For historical reasons, arguments can also be given as a comma-separated list.
+Z historických důvodů můžeme argumenty uvést i jako seznam oddělený čárkou.
-These three declarations mean the same:
+Tyto tři deklarace znamenají totéž:
```js
-new Function('a', 'b', 'return a + b'); // basic syntax
-new Function('a,b', 'return a + b'); // comma-separated
-new Function('a , b', 'return a + b'); // comma-separated with spaces
+new Function('a', 'b', 'return a + b'); // základní syntaxe
+new Function('a,b', 'return a + b'); // oddělené čárkou
+new Function('a , b', 'return a + b'); // oddělené čárkou s mezerami
```
-Functions created with `new Function`, have `[[Environment]]` referencing the global Lexical Environment, not the outer one. Hence, they cannot use outer variables. But that's actually good, because it insures us from errors. Passing parameters explicitly is a much better method architecturally and causes no problems with minifiers.
+Vlastnost `[[Environment]]` funkcí vytvořených pomocí `new Function` se odkazuje na globální lexikální prostředí, ne na vnější. Proto tyto funkce nemohou používat vnější proměnné. To je však ve skutečnosti dobře, protože nás to ochraňuje před chybami. Výslovné předávání parametrů je architektonicky mnohem lepší způsob a nezpůsobuje problémy s minifikátory.
diff --git a/1-js/06-advanced-functions/08-settimeout-setinterval/1-output-numbers-100ms/solution.md b/1-js/06-advanced-functions/08-settimeout-setinterval/1-output-numbers-100ms/solution.md
index b5b1da7a6..3f6350805 100644
--- a/1-js/06-advanced-functions/08-settimeout-setinterval/1-output-numbers-100ms/solution.md
+++ b/1-js/06-advanced-functions/08-settimeout-setinterval/1-output-numbers-100ms/solution.md
@@ -1,64 +1,64 @@
-Using `setInterval`:
+Pomocí `setInterval`:
```js run
-function printNumbers(from, to) {
- let current = from;
+function vypišČísla(začátek, konec) {
+ let aktuální = začátek;
- let timerId = setInterval(function() {
- alert(current);
- if (current == to) {
- clearInterval(timerId);
+ let idČasovače = setInterval(function() {
+ alert(aktuální);
+ if (aktuální == konec) {
+ clearInterval(idČasovače);
}
- current++;
+ aktuální++;
}, 1000);
}
-// usage:
-printNumbers(5, 10);
+// použití:
+vypišČísla(5, 10);
```
-Using nested `setTimeout`:
+Pomocí vnořeného `setTimeout`:
```js run
-function printNumbers(from, to) {
- let current = from;
+function vypišČísla(začátek, konec) {
+ let aktuální = začátek;
- setTimeout(function go() {
- alert(current);
- if (current < to) {
- setTimeout(go, 1000);
+ setTimeout(function spusť() {
+ alert(aktuální);
+ if (aktuální < konec) {
+ setTimeout(spusť, 1000);
}
- current++;
+ aktuální++;
}, 1000);
}
-// usage:
-printNumbers(5, 10);
+// použití:
+vypišČísla(5, 10);
```
-Note that in both solutions, there is an initial delay before the first output. The function is called after `1000ms` the first time.
+Všimněte si, že v obou řešeních je úvodní prodleva před prvním výstupem. Funkce je poprvé volána za `1000 ms`.
-If we also want the function to run immediately, then we can add an additional call on a separate line, like this:
+Jestliže chceme, aby se funkce spustila okamžitě, můžeme přidat další volání na samostatný řádek, například takto:
```js run
-function printNumbers(from, to) {
- let current = from;
+function vypišČísla(začátek, konec) {
+ let aktuální = začátek;
- function go() {
- alert(current);
- if (current == to) {
- clearInterval(timerId);
+ function spusť() {
+ alert(aktuální);
+ if (aktuální == konec) {
+ clearInterval(idČasovače);
}
- current++;
+ aktuální++;
}
*!*
- go();
+ spusť();
*/!*
- let timerId = setInterval(go, 1000);
+ let idČasovače = setInterval(spusť, 1000);
}
-printNumbers(5, 10);
+vypišČísla(5, 10);
```
diff --git a/1-js/06-advanced-functions/08-settimeout-setinterval/1-output-numbers-100ms/task.md b/1-js/06-advanced-functions/08-settimeout-setinterval/1-output-numbers-100ms/task.md
index 84bb0c39c..2dcbf2777 100644
--- a/1-js/06-advanced-functions/08-settimeout-setinterval/1-output-numbers-100ms/task.md
+++ b/1-js/06-advanced-functions/08-settimeout-setinterval/1-output-numbers-100ms/task.md
@@ -2,11 +2,11 @@ importance: 5
---
-# Output every second
+# Výstup každou sekundu
-Write a function `printNumbers(from, to)` that outputs a number every second, starting from `from` and ending with `to`.
+Napište funkci `vypišČísla(začátek, konec)`, která každou sekundu vypíše číslo, přičemž začne číslem `začátek` a skončí číslem `konec`.
-Make two variants of the solution.
+Vytvořte dvě varianty řešení.
-1. Using `setInterval`.
-2. Using nested `setTimeout`.
+1. Pomocí `setInterval`.
+2. Pomocí vnořeného `setTimeout`.
diff --git a/1-js/06-advanced-functions/08-settimeout-setinterval/4-settimeout-result/solution.md b/1-js/06-advanced-functions/08-settimeout-setinterval/4-settimeout-result/solution.md
index e652a3b36..1124d9621 100644
--- a/1-js/06-advanced-functions/08-settimeout-setinterval/4-settimeout-result/solution.md
+++ b/1-js/06-advanced-functions/08-settimeout-setinterval/4-settimeout-result/solution.md
@@ -1,14 +1,14 @@
-Any `setTimeout` will run only after the current code has finished.
+Každý `setTimeout` se spustí teprve po dokončení aktuálního kódu.
-The `i` will be the last one: `100000000`.
+Proměnná `i` bude obsahovat poslední hodnotu: `100000000`.
```js run
let i = 0;
setTimeout(() => alert(i), 100); // 100000000
-// assume that the time to execute this function is >100ms
+// předpokládáme, že doba běhu této funkce je větší než 100 ms
for(let j = 0; j < 100000000; j++) {
i++;
}
diff --git a/1-js/06-advanced-functions/08-settimeout-setinterval/4-settimeout-result/task.md b/1-js/06-advanced-functions/08-settimeout-setinterval/4-settimeout-result/task.md
index 667c8ffa6..308922fca 100644
--- a/1-js/06-advanced-functions/08-settimeout-setinterval/4-settimeout-result/task.md
+++ b/1-js/06-advanced-functions/08-settimeout-setinterval/4-settimeout-result/task.md
@@ -2,25 +2,25 @@ importance: 5
---
-# What will setTimeout show?
+# Co zobrazí setTimeout?
-In the code below there's a `setTimeout` call scheduled, then a heavy calculation is run, that takes more than 100ms to finish.
+V následujícím kódu je načasováno volání `setTimeout`, pak proběhne náročný výpočet, jehož dokončení bude trvat více než 100 ms.
-When will the scheduled function run?
+Kdy se načasovaná funkce spustí?
-1. After the loop.
-2. Before the loop.
-3. In the beginning of the loop.
+1. Po cyklu.
+2. Před cyklem.
+3. Na začátku cyklu.
-What is `alert` going to show?
+Co zobrazí `alert`?
```js
let i = 0;
setTimeout(() => alert(i), 100); // ?
-// assume that the time to execute this function is >100ms
+// předpokládáme, že doba výkonu této funkce je větší než 100 ms
for(let j = 0; j < 100000000; j++) {
i++;
}
diff --git a/1-js/06-advanced-functions/08-settimeout-setinterval/article.md b/1-js/06-advanced-functions/08-settimeout-setinterval/article.md
index f96959988..bc961cfd6 100644
--- a/1-js/06-advanced-functions/08-settimeout-setinterval/article.md
+++ b/1-js/06-advanced-functions/08-settimeout-setinterval/article.md
@@ -1,302 +1,302 @@
-# Scheduling: setTimeout and setInterval
+# Časování: setTimeout a setInterval
-We may decide to execute a function not right now, but at a certain time later. That's called "scheduling a call".
+Můžeme se rozhodnout, že funkci nespustíme právě teď, ale až za nějakou dobu. To se nazývá „časování volání“ („scheduling a call“).
-There are two methods for it:
+K tomu existují dvě metody:
-- `setTimeout` allows us to run a function once after the interval of time.
-- `setInterval` allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
+- `setTimeout` nám umožňuje spustit funkci jednou po uplynutí zadaného časového intervalu.
+- `setInterval` nám umožňuje spouštět funkci opakovaně, nejprve po uplynutí zadaného časového intervalu a pak bude neustále v tomto intervalu opakována.
-These methods are not a part of JavaScript specification. But most environments have the internal scheduler and provide these methods. In particular, they are supported in all browsers and Node.js.
+Tyto metody nejsou součástí specifikace JavaScriptu, ale většina prostředí obsahuje interní plánovač a tyto metody poskytuje. Konkrétně jsou podporovány ve všech prohlížečích a v Node.js.
## setTimeout
-The syntax:
+Syntaxe:
```js
-let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...)
+let idČasovače = setTimeout(funkce|kód, [prodleva], [arg1], [arg2], ...)
```
-Parameters:
+Parametry:
-`func|code`
-: Function or a string of code to execute.
-Usually, that's a function. For historical reasons, a string of code can be passed, but that's not recommended.
+`funkce|kód`
+: Funkce nebo řetězec kódu, který se má spustit.
+Obvykle to bývá funkce. Z historických důvodů lze předat i řetězec kódu, ale to se nedoporučuje.
-`delay`
-: The delay before run, in milliseconds (1000 ms = 1 second), by default 0.
+`prodleva`
+: Prodleva před spuštěním v milisekundách (1000 ms = 1 sekunda), standardně 0.
`arg1`, `arg2`...
-: Arguments for the function
+: Argumenty této funkce.
-For instance, this code calls `sayHi()` after one second:
+Například tento kód zavolá `řekniAhoj()` po uplynutí jedné sekundy:
```js run
-function sayHi() {
- alert('Hello');
+function řekniAhoj() {
+ alert('Ahoj');
}
*!*
-setTimeout(sayHi, 1000);
+setTimeout(řekniAhoj, 1000);
*/!*
```
-With arguments:
+S argumenty:
```js run
-function sayHi(phrase, who) {
- alert( phrase + ', ' + who );
+function řekniAhoj(věta, kdo) {
+ alert( věta + ', ' + kdo );
}
*!*
-setTimeout(sayHi, 1000, "Hello", "John"); // Hello, John
+setTimeout(řekniAhoj, 1000, "Ahoj", "Jan"); // Ahoj, Jan
*/!*
```
-If the first argument is a string, then JavaScript creates a function from it.
+Je-li první argument řetězec, pak z něj JavaScript vytvoří funkci.
-So, this will also work:
+Bude tedy fungovat i tohle:
```js run no-beautify
-setTimeout("alert('Hello')", 1000);
+setTimeout("alert('Ahoj')", 1000);
```
-But using strings is not recommended, use arrow functions instead of them, like this:
+Používání řetězců se však nedoporučuje, místo nich používejte šipkové funkce, například takto:
```js run no-beautify
-setTimeout(() => alert('Hello'), 1000);
+setTimeout(() => alert('Ahoj'), 1000);
```
-````smart header="Pass a function, but don't run it"
-Novice developers sometimes make a mistake by adding brackets `()` after the function:
+````smart header="Předejte funkci, ale nevolejte ji"
+Začínající vývojáři někdy dělají chybu v tom, že za funkci přidají závorky `()`:
```js
-// wrong!
-setTimeout(sayHi(), 1000);
+// špatně!
+setTimeout(řekniAhoj(), 1000);
```
-That doesn't work, because `setTimeout` expects a reference to a function. And here `sayHi()` runs the function, and the *result of its execution* is passed to `setTimeout`. In our case the result of `sayHi()` is `undefined` (the function returns nothing), so nothing is scheduled.
+To nefunguje, protože `setTimeout` očekává odkaz na funkci. A zde `řekniAhoj()` zavolá funkci a teprve *výsledek jejího volání* se předá funkci `setTimeout`. V našem případě výsledek `řekniAhoj()` je `undefined` (funkce nic nevrací), takže se nic nenačasuje.
````
-### Canceling with clearTimeout
+### Zrušení pomocí clearTimeout
-A call to `setTimeout` returns a "timer identifier" `timerId` that we can use to cancel the execution.
+Volání `setTimeout` vrátí „identifikátor časovače“ `idČasovače`, který můžeme použít ke zrušení načasovaného spuštění.
-The syntax to cancel:
+Syntaxe zrušení:
```js
-let timerId = setTimeout(...);
-clearTimeout(timerId);
+let idČasovače = setTimeout(...);
+clearTimeout(idČasovače);
```
-In the code below, we schedule the function and then cancel it (changed our mind). As a result, nothing happens:
+V následujícím kódu načasujeme funkci a pak ji zrušíme (rozmysleli jsme si to). Výsledkem bude, že se nic nestane:
```js run no-beautify
-let timerId = setTimeout(() => alert("never happens"), 1000);
-alert(timerId); // timer identifier
+let idČasovače = setTimeout(() => alert("tohle se nikdy nestane"), 1000);
+alert(idČasovače); // identifikátor časovače
-clearTimeout(timerId);
-alert(timerId); // same identifier (doesn't become null after canceling)
+clearTimeout(idČasovače);
+alert(idČasovače); // stejný identifikátor (po zrušení se nevynuloval)
```
-As we can see from `alert` output, in a browser the timer identifier is a number. In other environments, this can be something else. For instance, Node.js returns a timer object with additional methods.
+Jak vidíme z výstupu `alert`, v prohlížeči je identifikátorem časovače číslo. V jiných prostředích to může být něco jiného, například Node.js vrací objekt časovače s dalšími metodami.
-Again, there is no universal specification for these methods, so that's fine.
+Opakujeme, že pro tyto metody neexistuje žádná univerzální specifikace, takže je to v pořádku.
-For browsers, timers are described in the [timers section](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers) of HTML Living Standard.
+Pro prohlížeče jsou časovače popsány v [kapitole o časovačích](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers) HTML Living Standardu.
## setInterval
-The `setInterval` method has the same syntax as `setTimeout`:
+Metoda `setInterval` má stejnou syntaxi jako `setTimeout`:
```js
-let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...)
+let idČasovače = setInterval(funkce|kód, [prodleva], [arg1], [arg2], ...)
```
-All arguments have the same meaning. But unlike `setTimeout` it runs the function not only once, but regularly after the given interval of time.
+Všechny argumenty mají stejný význam. Na rozdíl od `setTimeout` však funkce nebude spuštěna jenom jednou, ale pravidelně vždy po uplynutí zadaného časového intervalu.
-To stop further calls, we should call `clearInterval(timerId)`.
+Chceme-li zastavit další volání, měli bychom zavolat `clearInterval(idČasovače)`.
-The following example will show the message every 2 seconds. After 5 seconds, the output is stopped:
+Následující příklad zobrazí zprávu každé 2 sekundy. Po 5 sekundách bude výstup zastaven:
```js run
-// repeat with the interval of 2 seconds
-let timerId = setInterval(() => alert('tick'), 2000);
+// opakovat s intervalem 2 sekundy
+let idČasovače = setInterval(() => alert('tik'), 2000);
-// after 5 seconds stop
-setTimeout(() => { clearInterval(timerId); alert('stop'); }, 5000);
+// konec po 5 sekundách
+setTimeout(() => { clearInterval(idČasovače); alert('stop'); }, 5000);
```
-```smart header="Time goes on while `alert` is shown"
-In most browsers, including Chrome and Firefox the internal timer continues "ticking" while showing `alert/confirm/prompt`.
+```smart header="Zatímco je zobrazen `alert`, čas plyne dál"
+Ve většině prohlížečů včetně Chrome a Firefoxu v době, kdy je zobrazeno `alert/confirm/prompt`, vnitřní časovač „tiká“ dál.
-So if you run the code above and don't dismiss the `alert` window for some time, then the next `alert` will be shown immediately as you do it. The actual interval between alerts will be shorter than 2 seconds.
+Když si tedy spustíte výše uvedený kód a okno `alert` nějakou dobu nezrušíte, pak bude následující `alert` zobrazen hned, jakmile to uděláte. Skutečný interval mezi zobrazeními tedy bude kratší než 2 sekundy.
```
-## Nested setTimeout
+## Vnořený setTimeout
-There are two ways of running something regularly.
+Existují dva způsoby, jak něco pravidelně spouštět.
-One is `setInterval`. The other one is a nested `setTimeout`, like this:
+První je `setInterval`. Druhý je vnořený `setTimeout`, například takto:
```js
-/** instead of:
-let timerId = setInterval(() => alert('tick'), 2000);
+/** namísto:
+let idČasovače = setInterval(() => alert('tik'), 2000);
*/
-let timerId = setTimeout(function tick() {
- alert('tick');
+let idČasovače = setTimeout(function tik() {
+ alert('tik');
*!*
- timerId = setTimeout(tick, 2000); // (*)
+ idČasovače = setTimeout(tik, 2000); // (*)
*/!*
}, 2000);
```
-The `setTimeout` above schedules the next call right at the end of the current one `(*)`.
+Uvedený `setTimeout` načasuje další volání na konci aktuálního na řádku `(*)`.
-The nested `setTimeout` is a more flexible method than `setInterval`. This way the next call may be scheduled differently, depending on the results of the current one.
+Vnořený `setTimeout` je flexibilnější metoda než `setInterval`. Tímto způsobem můžeme příští volání načasovat za jinou dobu, podle výsledků aktuálního volání.
-For instance, we need to write a service that sends a request to the server every 5 seconds asking for data, but in case the server is overloaded, it should increase the interval to 10, 20, 40 seconds...
+Například potřebujeme napsat službu, která každých 5 sekund pošle na server žádost o data, ale v případě, že je server přetížen, by tento interval měla zvýšit na 10, 20, 40 sekund...
-Here's the pseudocode:
+Zde je pseudokód:
```js
-let delay = 5000;
+let prodleva = 5000;
-let timerId = setTimeout(function request() {
- ...send request...
+let idČasovače = setTimeout(function požadavek() {
+ ...pošle požadavek...
- if (request failed due to server overload) {
- // increase the interval to the next run
- delay *= 2;
+ if (požadavek neuspěl kvůli přetížení serveru) {
+ // zvýšíme interval dalšího spuštění
+ prodleva *= 2;
}
- timerId = setTimeout(request, delay);
+ idČasovače = setTimeout(požadavek, prodleva);
-}, delay);
+}, prodleva);
```
+A jestliže funkce, které časujeme, zatěžují CPU, můžeme měřit dobu, jakou trvá jejich spuštění, a naplánovat si další volání na dříve nebo později.
-And if the functions that we're scheduling are CPU-hungry, then we can measure the time taken by the execution and plan the next call sooner or later.
+**Vnořený `setTimeout` nám umožňuje nastavovat prodlevu mezi voláními přesněji než `setInterval`.**
-**Nested `setTimeout` allows to set the delay between the executions more precisely than `setInterval`.**
-
-Let's compare two code fragments. The first one uses `setInterval`:
+Porovnejme si dva fragmenty kódu. První používá `setInterval`:
```js
let i = 1;
setInterval(function() {
- func(i++);
+ funkce(i++);
}, 100);
```
-The second one uses nested `setTimeout`:
+Druhý používá vnořený `setTimeout`:
```js
let i = 1;
-setTimeout(function run() {
- func(i++);
- setTimeout(run, 100);
+setTimeout(function spusť() {
+ funkce(i++);
+ setTimeout(spusť, 100);
}, 100);
```
-For `setInterval` the internal scheduler will run `func(i++)` every 100ms:
+Pro `setInterval` vnitřní plánovač spustí `funkce(i++)` každých 100 ms:

-Did you notice?
+Všimli jste si?
-**The real delay between `func` calls for `setInterval` is less than in the code!**
+**Skutečná prodleva mezi voláními `funkce` pro `setInterval` je nižší, než uvedená v kódu!**
-That's normal, because the time taken by `func`'s execution "consumes" a part of the interval.
+To je normální, protože doba, kterou zabere výkon `funkce`, „spotřebuje“ část intervalu.
-It is possible that `func`'s execution turns out to be longer than we expected and takes more than 100ms.
+Může se stát, že výkon `funkce` bude trvat déle, než jsme očekávali, a vyžádá si více než 100 ms.
-In this case the engine waits for `func` to complete, then checks the scheduler and if the time is up, runs it again *immediately*.
+V takovém případě motor počká, až se `funkce` dokončí, pak zkontroluje plánovač, a pokud jeho čas vypršel, spustí funkci *okamžitě* znovu.
-In the edge case, if the function always executes longer than `delay` ms, then the calls will happen without a pause at all.
+V krajním případě, jestliže výkon funkce trvá vždy déle než `prodleva` ms, bude k voláním docházet úplně bez prodlevy.
-And here is the picture for the nested `setTimeout`:
+A zde je obrázek pro vnořený `setTimeout`:

-**The nested `setTimeout` guarantees the fixed delay (here 100ms).**
+**Vnořený `setTimeout` zaručuje pevnou prodlevu (zde 100 ms).**
-That's because a new call is planned at the end of the previous one.
+Je to proto, že nové volání je naplánováno na konci předchozího.
-````smart header="Garbage collection and setInterval/setTimeout callback"
-When a function is passed in `setInterval/setTimeout`, an internal reference is created to it and saved in the scheduler. It prevents the function from being garbage collected, even if there are no other references to it.
+````smart header="Sběr odpadků a callback funkce setInterval/setTimeout"
+Když je do `setInterval/setTimeout` předána funkce, vytvoří se na ni interní odkaz a ten se uloží do plánovače. To brání sběrači odpadků, aby funkci odstranil, i když na ni nejsou žádné jiné odkazy.
```js
-// the function stays in memory until the scheduler calls it
+// funkce zůstane v paměti, dokud ji plánovač nezavolá
setTimeout(function() {...}, 100);
```
-For `setInterval` the function stays in memory until `clearInterval` is called.
+Pro `setInterval` funkce zůstane v paměti, dokud není zavolán `clearInterval`.
-There's a side effect. A function references the outer lexical environment, so, while it lives, outer variables live too. They may take much more memory than the function itself. So when we don't need the scheduled function anymore, it's better to cancel it, even if it's very small.
+To má vedlejší efekt. Funkce se odkazuje na vnější lexikální prostředí, takže dokud existuje, existují i vnější proměnné. Ty mohou zabrat mnohem více paměti než samotná funkce. Když tedy načasovanou funkci už nepotřebujeme, je lepší ji zrušit, i kdyby byla velmi malá.
````
-## Zero delay setTimeout
+## setTimeout s nulovou prodlevou
-There's a special use case: `setTimeout(func, 0)`, or just `setTimeout(func)`.
+Existuje speciální způsob použití: `setTimeout(funkce, 0)` nebo jen `setTimeout(funkce)`.
-This schedules the execution of `func` as soon as possible. But the scheduler will invoke it only after the currently executing script is complete.
+To načasuje výkon `funkce` na co nejdříve. Plánovač ji však spustí až poté, co bude dokončen aktuálně běžící skript.
-So the function is scheduled to run "right after" the current script.
+Funkce je tedy načasována ke spuštění „hned po“ aktuálním skriptu.
-For instance, this outputs "Hello", then immediately "World":
+Například tohle vypíše „Ahoj“ a hned pak „světe“:
```js run
-setTimeout(() => alert("World"));
+setTimeout(() => alert("světe"));
-alert("Hello");
+alert("Ahoj");
```
-The first line "puts the call into calendar after 0ms". But the scheduler will only "check the calendar" after the current script is complete, so `"Hello"` is first, and `"World"` -- after it.
+První řádek „uloží volání do kalendáře za 0 ms“. Avšak plánovač „zkontroluje kalendář“ až poté, co bude aktuální skript dokončen, takže `"Ahoj"` půjde jako první a `"světe"` až po něm.
+
+V prohlížečích existují i pokročilejší způsoby použití načasování s nulovou prodlevou, které probereme v kapitole .
-There are also advanced browser-related use cases of zero-delay timeout, that we'll discuss in the chapter .
+````smart header="Nulová prodleva není ve skutečnosti nulová (v prohlížeči)"
-````smart header="Zero delay is in fact not zero (in a browser)"
-In the browser, there's a limitation of how often nested timers can run. The [HTML Living Standard](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers) says: "after five nested timers, the interval is forced to be at least 4 milliseconds.".
+V prohlížeči je omezení, jak často se mohou vnořené časovače spouštět. [HTML Living Standard](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers) říká: „po pěti vnořených časovačích musí být interval alespoň 4 milisekundy.“
-Let's demonstrate what it means with the example below. The `setTimeout` call in it re-schedules itself with zero delay. Each call remembers the real time from the previous one in the `times` array. What do the real delays look like? Let's see:
+Na následujícím příkladu si předvedeme, co to znamená. Volání `setTimeout` v něm načasuje samo sebe s nulovou prodlevou. Každé volání si pamatuje v poli `časy` skutečný čas, který uplynul od předchozího. Jak budou vypadat skutečné prodlevy? Podívejme se:
```js run
-let start = Date.now();
-let times = [];
+let začátek = Date.now();
+let časy = [];
-setTimeout(function run() {
- times.push(Date.now() - start); // remember delay from the previous call
+setTimeout(function spusť() {
+ časy.push(Date.now() - začátek); // zapamatujeme si prodlevu od předchozího volání
- if (start + 100 < Date.now()) alert(times); // show the delays after 100ms
- else setTimeout(run); // else re-schedule
+ if (začátek + 100 < Date.now()) alert(časy); // za 100 ms zobrazíme prodlevy
+ else setTimeout(spusť); // jinak znovu načasujeme
});
-// an example of the output:
+// příklad výstupu:
// 1,1,1,1,9,15,20,24,30,35,40,45,50,55,59,64,70,75,80,85,90,95,100
```
-First timers run immediately (just as written in the spec), and then we see `9, 15, 20, 24...`. The 4+ ms obligatory delay between invocations comes into play.
+Nejprve se časovače spustí okamžitě (tak, jak je uvedeno ve specifikaci) a pak vidíme `9, 15, 20, 24...`. Povinná prodleva aspoň 4 ms mezi voláními vstupuje do hry.
-The similar thing happens if we use `setInterval` instead of `setTimeout`: `setInterval(f)` runs `f` few times with zero-delay, and afterwards with 4+ ms delay.
+Podobná věc se stane, jestliže použijeme `setInterval` namísto `setTimeout`: `setInterval(f)` spustí `f` několikrát s nulovou prodlevou a poté s prodlevou nejméně 4 ms.
-That limitation comes from ancient times and many scripts rely on it, so it exists for historical reasons.
+Toto omezení pochází ze starých časů a mnoho skriptů se na ně spoléhá, takže existuje z historických důvodů.
-For server-side JavaScript, that limitation does not exist, and there exist other ways to schedule an immediate asynchronous job, like [setImmediate](https://nodejs.org/api/timers.html#timers_setimmediate_callback_args) for Node.js. So this note is browser-specific.
+Pro JavaScript na straně serveru toto omezení neexistuje a jsou tam jiné způsoby, jak načasovat okamžitou asynchronní činnost, například [setImmediate](https://nodejs.org/api/timers.html#timers_setimmediate_callback_args) pro Node.js. Tato poznámka je tedy specifická pro prohlížeče.
````
-## Summary
+## Shrnutí
-- Methods `setTimeout(func, delay, ...args)` and `setInterval(func, delay, ...args)` allow us to run the `func` once/regularly after `delay` milliseconds.
-- To cancel the execution, we should call `clearTimeout/clearInterval` with the value returned by `setTimeout/setInterval`.
-- Nested `setTimeout` calls are a more flexible alternative to `setInterval`, allowing us to set the time *between* executions more precisely.
-- Zero delay scheduling with `setTimeout(func, 0)` (the same as `setTimeout(func)`) is used to schedule the call "as soon as possible, but after the current script is complete".
-- The browser limits the minimal delay for five or more nested calls of `setTimeout` or for `setInterval` (after 5th call) to 4ms. That's for historical reasons.
+- Metody `setTimeout(funkce, prodleva, ...argumenty)` a `setInterval(funkce, prodleva, ...argumenty)` nám umožňují spustit funkci `funkce` jednou/pravidelně po `prodleva` milisekundách.
+- Chceme-li spuštění zrušit, měli bychom volat `clearTimeout/clearInterval` s hodnotou, kterou vrátila funkce `setTimeout/setInterval`.
+- Flexibilnější alternativou k `setInterval` jsou vnořená volání `setTimeout`, která nám umožňují nastavit čas *mezi* voláními přesněji.
+- Nulová prodleva v `setTimeout(funkce, 0)` (totéž jako `setTimeout(funkce)`) se používá k načasování volání „co nejdříve, ale až po dokončení aktuálního skriptu“.
+- Prohlížeč omezuje minimální prodlevu pro pět nebo více vnořených volání `setTimeout` nebo pro `setInterval` (po 5. volání) na 4 ms. Je tomu tak z historických důvodů.
-Please note that all scheduling methods do not *guarantee* the exact delay.
+Prosíme všimněte si, že žádná časovací metoda *nezaručuje* přesnou prodlevu.
-For example, the in-browser timer may slow down for a lot of reasons:
-- The CPU is overloaded.
-- The browser tab is in the background mode.
-- The laptop is on battery saving mode.
+Například časovač v prohlížeči může zpomalit z mnoha důvodů:
+- CPU je přetížen.
+- Záložka prohlížeče běží na pozadí.
+- Laptop je v režimu úspory baterie.
-All that may increase the minimal timer resolution (the minimal delay) to 300ms or even 1000ms depending on the browser and OS-level performance settings.
+To všechno může zvýšit minimální rozlišení časovače (minimální prodlevu) na 300 ms nebo dokonce 1000 ms v závislosti na prohlížeči a nastavení výkonu na úrovni OS.
diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/_js.view/solution.js b/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/_js.view/solution.js
index d5a09efb3..13daa3a8b 100644
--- a/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/_js.view/solution.js
+++ b/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/_js.view/solution.js
@@ -1,12 +1,13 @@
-function spy(func) {
+function špión(funkce) {
- function wrapper(...args) {
- // using ...args instead of arguments to store "real" array in wrapper.calls
- wrapper.calls.push(args);
- return func.apply(this, args);
+ function obal(...argumenty) {
+ // použijeme ...argumenty místo arguments, abychom do obal.volání uložili „skutečné“ pole
+ obal.volání.push(argumenty);
+ return funkce.apply(this, argumenty);
}
- wrapper.calls = [];
+ obal.volání = [];
- return wrapper;
+ return obal;
}
+
\ No newline at end of file
diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/_js.view/source.js b/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/_js.view/source.js
index 38da0105f..7ad5afa68 100644
--- a/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/_js.view/source.js
+++ b/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/_js.view/source.js
@@ -1,5 +1,5 @@
-function spy(func) {
- // your code
+function špión(funkce) {
+ // váš kód
}
diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/_js.view/test.js b/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/_js.view/test.js
index 5adfcb978..f89cd0808 100644
--- a/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/_js.view/test.js
+++ b/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/_js.view/test.js
@@ -1,44 +1,44 @@
-describe("spy", function() {
- it("records calls into its property", function() {
- function work() {}
+describe("špión", function() {
+ it("zapisuje volání do své vlastnosti", function() {
+ function práce() {}
- work = spy(work);
- assert.deepEqual(work.calls, []);
+ práce = špión(práce);
+ assert.deepEqual(práce.volání, []);
- work(1, 2);
- assert.deepEqual(work.calls, [
+ práce(1, 2);
+ assert.deepEqual(práce.volání, [
[1, 2]
]);
- work(3, 4);
- assert.deepEqual(work.calls, [
+ práce(3, 4);
+ assert.deepEqual(práce.volání, [
[1, 2],
[3, 4]
]);
});
- it("transparently wraps functions", function() {
+ it("transparentně obaluje funkce", function() {
- let sum = sinon.spy((a, b) => a + b);
+ let sečti = sinon.spy((a, b) => a + b);
- let wrappedSum = spy(sum);
+ let obalenéSečti = špión(sečti);
- assert.equal(wrappedSum(1, 2), 3);
- assert(sum.calledWith(1, 2));
+ assert.equal(obalenéSečti(1, 2), 3);
+ assert(sečti.calledWith(1, 2));
});
- it("transparently wraps methods", function() {
+ it("transparentně obaluje metody", function() {
- let calc = {
- sum: sinon.spy((a, b) => a + b)
+ let vypočítej = {
+ sečti: sinon.spy((a, b) => a + b)
};
- calc.wrappedSum = spy(calc.sum);
+ vypočítej.obalenéSečti = špión(vypočítej.sečti);
- assert.equal(calc.wrappedSum(1, 2), 3);
- assert(calc.sum.calledWith(1, 2));
- assert(calc.sum.calledOn(calc));
+ assert.equal(vypočítej.obalenéSečti(1, 2), 3);
+ assert(vypočítej.sečti.calledWith(1, 2));
+ assert(vypočítej.sečti.calledOn(vypočítej));
});
});
diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/solution.md b/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/solution.md
index 0c8a211b4..d75d1870e 100644
--- a/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/solution.md
+++ b/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/solution.md
@@ -1 +1 @@
-The wrapper returned by `spy(f)` should store all arguments and then use `f.apply` to forward the call.
+Obal, který vrátí `špión(f)`, by si měl uložit všechny argumenty a pak pomocí `f.apply` přesměrovat volání.
diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/task.md b/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/task.md
index a3843107c..bfa09fd08 100644
--- a/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/task.md
+++ b/1-js/06-advanced-functions/09-call-apply-decorators/01-spy-decorator/task.md
@@ -2,29 +2,29 @@ importance: 5
---
-# Spy decorator
+# Špiónský dekorátor
-Create a decorator `spy(func)` that should return a wrapper that saves all calls to function in its `calls` property.
+Vytvořte dekorátor `špión(funkce)`, který by měl vrátit obal, který si bude ukládat všechna volání funkce do své vlastnosti `volání`.
-Every call is saved as an array of arguments.
+Každé volání bude uloženo jako pole argumentů.
-For instance:
+Například:
```js
-function work(a, b) {
- alert( a + b ); // work is an arbitrary function or method
+function práce(a, b) {
+ alert( a + b ); // práce je jakákoli funkce nebo metoda
}
*!*
-work = spy(work);
+práce = špión(práce);
*/!*
-work(1, 2); // 3
-work(4, 5); // 9
+práce(1, 2); // 3
+práce(4, 5); // 9
-for (let args of work.calls) {
- alert( 'call:' + args.join() ); // "call:1,2", "call:4,5"
+for (let argumenty of práce.volání) {
+ alert( 'volání:' + argumenty.join() ); // "volání:1,2", "volání:4,5"
}
```
-P.S. That decorator is sometimes useful for unit-testing. Its advanced form is `sinon.spy` in [Sinon.JS](http://sinonjs.org/) library.
+P.S. Takový dekorátor je někdy užitečný pro jednotkové testování. Jeho pokročilá forma je `sinon.spy` v knihovně [Sinon.JS](http://sinonjs.org/).
diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/_js.view/solution.js b/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/_js.view/solution.js
index 127cff988..ec80a9e66 100644
--- a/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/_js.view/solution.js
+++ b/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/_js.view/solution.js
@@ -1,4 +1,4 @@
-function delay(f, ms) {
+function zpozdi(f, ms) {
return function() {
setTimeout(() => f.apply(this, arguments), ms);
diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/_js.view/test.js b/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/_js.view/test.js
index d9295da51..4cf787a4f 100644
--- a/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/_js.view/test.js
+++ b/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/_js.view/test.js
@@ -1,46 +1,46 @@
-describe("delay", function() {
+describe("zpozdi", function() {
before(function() {
- this.clock = sinon.useFakeTimers();
+ this.hodiny = sinon.useFakeTimers();
});
after(function() {
- this.clock.restore();
+ this.hodiny.restore();
});
- it("calls the function after the specified timeout", function() {
- let start = Date.now();
+ it("volá funkci až po specifikované době", function() {
+ let začátek = Date.now();
function f(x) {
- assert.equal(Date.now() - start, 1000);
+ assert.equal(Date.now() - začátek, 1000);
}
f = sinon.spy(f);
- let f1000 = delay(f, 1000);
+ let f1000 = zpozdi(f, 1000);
f1000("test");
- this.clock.tick(2000);
- assert(f.calledOnce, 'calledOnce check fails');
+ this.hodiny.tick(2000);
+ assert(f.calledOnce, 'ověření calledOnce selhalo');
});
- it("passes arguments and this", function() {
- let start = Date.now();
- let user = {
- sayHi: function(phrase, who) {
- assert.equal(this, user);
- assert.equal(phrase, "Hello");
- assert.equal(who, "John");
- assert.equal(Date.now() - start, 1500);
+ it("předává argumenty a this", function() {
+ let začátek = Date.now();
+ let uživatel = {
+ řekniAhoj: function(věta, kdo) {
+ assert.equal(this, uživatel);
+ assert.equal(věta, "Ahoj");
+ assert.equal(kdo, "Jan");
+ assert.equal(Date.now() - začátek, 1500);
}
};
- user.sayHi = sinon.spy(user.sayHi);
+ uživatel.řekniAhoj = sinon.spy(uživatel.řekniAhoj);
- let spy = user.sayHi;
- user.sayHi = delay(user.sayHi, 1500);
+ let špión = uživatel.řekniAhoj;
+ uživatel.řekniAhoj = zpozdi(uživatel.řekniAhoj, 1500);
- user.sayHi("Hello", "John");
+ uživatel.řekniAhoj("Ahoj", "Jan");
- this.clock.tick(2000);
+ this.hodiny.tick(2000);
- assert(spy.calledOnce, 'calledOnce check failed');
+ assert(špión.calledOnce, 'ověření calledOnce selhalo');
});
});
diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/solution.md b/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/solution.md
index 24bb4d448..15a434536 100644
--- a/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/solution.md
+++ b/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/solution.md
@@ -1,7 +1,7 @@
-The solution:
+Řešení:
```js run demo
-function delay(f, ms) {
+function zpozdi(f, ms) {
return function() {
setTimeout(() => f.apply(this, arguments), ms);
@@ -9,24 +9,24 @@ function delay(f, ms) {
}
-let f1000 = delay(alert, 1000);
+let f1000 = zpozdi(alert, 1000);
-f1000("test"); // shows "test" after 1000ms
+f1000("test"); // zobrazí "test" za 1000 ms
```
-Please note how an arrow function is used here. As we know, arrow functions do not have own `this` and `arguments`, so `f.apply(this, arguments)` takes `this` and `arguments` from the wrapper.
+Prosíme všimněte si, jak je zde použita šipková funkce. Jak víme, šipkové funkce nemají vlastní `this` ani `arguments`, takže `f.apply(this, arguments)` převezme `this` a `arguments` z obalu.
-If we pass a regular function, `setTimeout` would call it without arguments and `this=window` (assuming we're in the browser).
+Předáme-li běžnou funkci, `setTimeout` ji bude volat bez argumentů a `this=window` (za předpokladu, že jsme v prohlížeči).
-We still can pass the right `this` by using an intermediate variable, but that's a little bit more cumbersome:
+Můžeme také předávat skutečné `this` pomocí mezilehlé proměnné, ale to je trochu pracnější:
```js
-function delay(f, ms) {
+function zpozdi(f, ms) {
- return function(...args) {
- let savedThis = this; // store this into an intermediate variable
+ return function(...argumenty) {
+ let uloženéThis = this; // uloží this do mezilehlé proměnné
setTimeout(function() {
- f.apply(savedThis, args); // use it here
+ f.apply(uloženéThis, argumenty); // zde ji použijeme
}, ms);
};
diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/task.md b/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/task.md
index c04c68d7e..a78b53de8 100644
--- a/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/task.md
+++ b/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/task.md
@@ -2,25 +2,25 @@ importance: 5
---
-# Delaying decorator
+# Zpožďovací dekorátor
-Create a decorator `delay(f, ms)` that delays each call of `f` by `ms` milliseconds.
+Vytvořte dekorátor `zpozdi(f, ms)`, který zpozdí každé volání funkce `f` o `ms` milisekund.
-For instance:
+Například:
```js
function f(x) {
alert(x);
}
-// create wrappers
-let f1000 = delay(f, 1000);
-let f1500 = delay(f, 1500);
+// vytvoření obalů
+let f1000 = zpozdi(f, 1000);
+let f1500 = zpozdi(f, 1500);
-f1000("test"); // shows "test" after 1000ms
-f1500("test"); // shows "test" after 1500ms
+f1000("test"); // zobrazí "test" za 1000 ms
+f1500("test"); // zobrazí "test" za 1500 ms
```
-In other words, `delay(f, ms)` returns a "delayed by `ms`" variant of `f`.
+Jinými slovy, `zpozdi(f, ms)` vrátí variantu `f` „zpožděnou o `ms`“.
-In the code above, `f` is a function of a single argument, but your solution should pass all arguments and the context `this`.
+V uvedeném kódu je `f` funkce s jediným argumentem, ale vaše řešení by mělo předávat všechny argumenty a kontextové `this`.
diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/_js.view/solution.js b/1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/_js.view/solution.js
index 661dd0cf4..16bc6bc57 100644
--- a/1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/_js.view/solution.js
+++ b/1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/_js.view/solution.js
@@ -1,7 +1,7 @@
-function debounce(func, ms) {
- let timeout;
+function vyčkej(funkce, ms) {
+ let časovač;
return function() {
- clearTimeout(timeout);
- timeout = setTimeout(() => func.apply(this, arguments), ms);
+ clearTimeout(časovač);
+ časovač = setTimeout(() => funkce.apply(this, arguments), ms);
};
}
diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/_js.view/test.js b/1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/_js.view/test.js
index 750e649f8..558220a13 100644
--- a/1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/_js.view/test.js
+++ b/1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/_js.view/test.js
@@ -1,48 +1,48 @@
-describe('debounce', function () {
+describe('vyčkej', function () {
before(function () {
- this.clock = sinon.useFakeTimers();
+ this.hodiny = sinon.useFakeTimers();
});
after(function () {
- this.clock.restore();
+ this.hodiny.restore();
});
- it('for one call - runs it after given ms', function () {
+ it('pro jedno volání - spustí je po zadané době v ms', function () {
const f = sinon.spy();
- const debounced = debounce(f, 1000);
+ const vyčkáváno = vyčkej(f, 1000);
- debounced('test');
- assert(f.notCalled, 'not called immediately');
- this.clock.tick(1000);
- assert(f.calledOnceWith('test'), 'called after 1000ms');
+ vyčkáváno('test');
+ assert(f.notCalled, 'nevolá se okamžitě');
+ this.hodiny.tick(1000);
+ assert(f.calledOnceWith('test'), 'voláno po 1000 ms');
});
- it('for 3 calls - runs the last one after given ms', function () {
+ it('pro 3 volání - spustí poslední po zadané době v ms', function () {
const f = sinon.spy();
- const debounced = debounce(f, 1000);
+ const vyčkáváno = vyčkej(f, 1000);
- debounced('a');
- setTimeout(() => debounced('b'), 200); // ignored (too early)
- setTimeout(() => debounced('c'), 500); // runs (1000 ms passed)
- this.clock.tick(1000);
+ vyčkáváno('a');
+ setTimeout(() => vyčkáváno('b'), 200); // ignorováno (příliš brzy)
+ setTimeout(() => vyčkáváno('c'), 500); // spustí se (1000 ms uplynulo)
+ this.hodiny.tick(1000);
- assert(f.notCalled, 'not called after 1000ms');
+ assert(f.notCalled, 'nevoláno po 1000 ms');
- this.clock.tick(500);
+ this.hodiny.tick(500);
- assert(f.calledOnceWith('c'), 'called after 1500ms');
+ assert(f.calledOnceWith('c'), 'voláno po 1500 ms');
});
- it('keeps the context of the call', function () {
+ it('udržuje si kontext volání', function () {
let obj = {
f() {
assert.equal(this, obj);
},
};
- obj.f = debounce(obj.f, 1000);
+ obj.f = vyčkej(obj.f, 1000);
obj.f('test');
- this.clock.tick(5000);
+ this.hodiny.tick(5000);
});
});
diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/debounce.view/index.html b/1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/debounce.view/index.html
index e3b4d5842..b03998aa2 100644
--- a/1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/debounce.view/index.html
+++ b/1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/debounce.view/index.html
@@ -1,22 +1,22 @@
-Function handler is called on this input:
+Funkce handler je volána na tomto vstupu:
-Debounced function debounce(handler, 1000) is called on this input:
+Vyčkávací funkce debounce(handler, 1000) je volána na tomto vstupu: