Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

1.14.3#224

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
otmon76 merged 6 commits intojavascript-tutorial:masterfromotmon76:otmon76-1.14.3
Jun 4, 2025
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
<!doctype html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Function <code>handler</code>is called on this input:
Funkce <code>handler</code>je volána na tomto vstupu:
<br>
<input id="input1" placeholder="type here">

<p>

Debounced function <code>debounce(handler, 1000)</code>is called on this input:
Vyčkávací funkce <code>debounce(handler, 1000)</code>je volána na tomto vstupu:
<br>
<input id="input2" placeholder="type here">

<p>
<button id="result">The <code>handler</code>puts the result here</button>
<button id="result">Funkce <code>handler</code>umístí výsledek sem</button>

<script>
function handler(event) {
result.innerHTML =event.target.value;
function handler(událost) {
result.innerHTML =událost.target.value;
}

input1.oninput = handler;
Expand Down
152 changes: 76 additions & 76 deletions1-js/99-js-misc/03-currying-partials/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,21 +3,21 @@ libs:

---

#Currying
#Curryování

[Currying](https://en.wikipedia.org/wiki/Currying)is an advanced technique of working with functions. It's used not only in JavaScript, but in other languages as well.
[Curryování neboli currying](https://en.wikipedia.org/wiki/Currying)je pokročilá technika práce s funkcemi. Používá se nejen v JavaScriptu, ale i v jiných jazycích.

Currying is a transformation of functions that translates a function from callable as`f(a, b, c)`into callable as `f(a)(b)(c)`.
Curryování je transformace funkce, která přeloží funkci volatelnou způsobem`f(a, b, c)`na funkci volatelnou způsobem `f(a)(b)(c)`.

Currying doesn't call a function. It just transforms it.
Curryování nevolá funkci, jen ji transformuje.

Let's see an example first, to better understand what we're talking about, and then practical applications.
Nejprve se podívejme na příklad, abychom lépe porozuměli tomu, o čem se tady mluví, a pak na praktické aplikace.

We'll create a helper function`curry(f)` that performs currying for a two-argument`f`.In other words, `curry(f)`for two-argument`f(a, b)`translates it into a function that runs as `f(a)(b)`:
Vytvořme pomocnou funkci`curry(f)`, která provádí curryování dvouargumentové funkce`f`.Jinými slovy, `curry(f)`na dvouargumentové funkci`f(a, b)`ji přeloží na funkci, která se bude spouštět jako `f(a)(b)`:

```js run
*!*
function curry(f) { // curry(f)does the currying transform
function curry(f) { // curry(f)provede curryovací transformaci
return function(a) {
return function(b) {
return f(a, b);
Expand All@@ -26,163 +26,163 @@ function curry(f) { // curry(f) does the currying transform
}
*/!*

//usage
functionsum(a, b) {
//použití
functionsoučet(a, b) {
return a + b;
}

letcurriedSum = curry(sum);
letcurryovanýSoučet = curry(součet);

alert(curriedSum(1)(2) ); // 3
alert(curryovanýSoučet(1)(2) ); // 3
```

As you can see, the implementation is straightforward: it's just two wrappers.
Jak vidíte, implementace je přímočará: jsou to pouhé dva obaly.

-The result of`curry(func)`is a wrapper `function(a)`.
-When it is called like `curriedSum(1)`,theargumentis saved in the Lexical Environment, and a new wrapper is returned `function(b)`.
-Then this wrapper is called with`2`as an argument, and it passes the call to the original `sum`.
-Výsledkem`curry(func)`je obal `function(a)`.
-Když je zavolán způsobem `curryovanýSoučet(1)`, argumentse uloží do lexikálního prostředí a vrátí se nový obal `function(b)`.
-Pak je tento obal volán s argumentem`2`a předá volání původní funkci `součet`.

More advanced implementations of currying, such as[_.curry](https://lodash.com/docs#curry)from lodash library, return a wrapper that allows a function to be called both normally and partially:
Pokročilejší implementace curryování, např.[_.curry](https://lodash.com/docs#curry)z knihovny lodash, vrátí obal, který umožní volat funkci jak obvyklým způsobem, tak parciálně:

```js run
functionsum(a, b) {
functionsoučet(a, b) {
return a + b;
}

letcurriedSum = _.curry(sum); //using _.curryfrom lodash library
letcurryovanýSoučet = _.curry(součet); //použijeme _.curryz knihovny lodash

alert(curriedSum(1, 2) ); // 3,still callable normally
alert(curriedSum(1)(2) ); // 3,called partially
alert(curryovanýSoučet(1, 2) ); // 3,stále volatelná normálně
alert(curryovanýSoučet(1)(2) ); // 3,voláno parciálně
```

##Currying? What for?
##Curryování? K čemu to je?

To understand the benefits we need a worthy real-life example.
Abychom pochopili výhody, potřebujeme cenný příklad z reálného života.

For instance, we have the logging function`log(date, importance, message)` that formats and outputs the information. In real projects such functions have many useful features like sending logs over the network, here we'll just use `alert`:
Mějme například logovací funkci`log(datum, důležitost, zpráva)`, která naformátuje a vypíše zadané informace. Ve skutečných projektech mají takové funkce mnoho užitečných možností, např. posílání logů po síti, zde jenom zavoláme `alert`:

```js
function log(date, importance, message) {
alert(`[${date.getHours()}:${date.getMinutes()}] [${importance}] ${message}`);
function log(datum, důležitost, zpráva) {
alert(`[${datum.getHours()}:${datum.getMinutes()}] [${důležitost}] ${zpráva}`);
}
```

Let's curry it!
Zcurryujme ji!

```js
log = _.curry(log);
```

After that `log`works normally:
Pak bude `log`fungovat normálně:

```js
log(new Date(), "DEBUG", "some debug"); // log(a, b, c)
log(new Date(), "LADĚNÍ", "nějaké ladění"); // log(a, b, c)
```

...But also works in the curried form:
...Ale bude fungovat i v curryované formě:

```js
log(new Date())("DEBUG")("some debug"); // log(a)(b)(c)
log(new Date())("LADĚNÍ")("nějaké ladění"); // log(a)(b)(c)
```

Now we can easily make a convenience function for current logs:
Nyní můžeme snadno vytvořit pohodlnou funkci pro aktuální logování:

```js
//logNow will be the partial oflogwith fixed first argument
letlogNow = log(new Date());
//logNyní bude parciálnílogs pevným prvním argumentem
letlogNyní = log(new Date());

//use it
logNow("INFO", "message"); // [HH:mm] INFOmessage
//použijeme ji
logNyní("INFO", "zpráva"); // [HH:mm] INFOzpráva
```

Now `logNow` is `log`with fixed first argument, in other words "partially applied function" or "partial" for short.
Nyní `logNyní` je `log`s pevným prvním argumentem, jinými slovy „parciálně aplikovaná funkce“ nebo krátce „parciální funkce“.

We can go further and make a convenience function for current debug logs:
Můžeme jít dál a vytvořit pohodlnou funkci pro aktuální logování ladění:

```js
letdebugNow =logNow("DEBUG");
letladěníNyní =logNyní("LADĚNÍ");

debugNow("message"); // [HH:mm]DEBUG message
laděníNyní("zpráva"); // [HH:mm]LADĚNÍ zpráva
```

So:
1.We didn't lose anything after currying: `log`is still callable normally.
2.We can easily generate partial functions such as for today's logs.
Tedy:
1.Po curryování nic neztratíme: `log`se stále dá volat běžným způsobem.
2.Můžeme snadno generovat parciální funkce, např. pro logování s dnešním datem.

##Advanced curry implementation
##Pokročilá implementace curryování

In case you'd like to get in to the details, here's the "advanced" curry implementation for multi-argument functions that we could use above.
Pro případ, že byste chtěli zajít do detailů, je zde „pokročilá“ implementace curryování pro víceargumentové funkce, kterou bychom mohli použít výše.

It's pretty short:
Je opravdu krátká:

```js
function curry(func) {
function curry(funkce) {

return functioncurried(...args) {
if (args.length >=func.length) {
returnfunc.apply(this, args);
return functioncurryovaná(...args) {
if (args.length >=funkce.length) {
returnfunkce.apply(this, args);
} else {
return function(...args2) {
returncurried.apply(this, args.concat(args2));
returncurryovaná.apply(this, args.concat(args2));
}
}
};

}
```

Usage examples:
Příklady použití:

```js
functionsum(a, b, c) {
functionsoučet(a, b, c) {
return a + b + c;
}

letcurriedSum = curry(sum);
letcurryovanýSoučet = curry(součet);

alert(curriedSum(1, 2, 3) ); // 6,still callable normally
alert(curriedSum(1)(2,3) ); // 6,currying of 1st arg
alert(curriedSum(1)(2)(3) ); // 6,full currying
alert(curryovanýSoučet(1, 2, 3) ); // 6,stále normálně volatelná
alert(curryovanýSoučet(1)(2,3) ); // 6,curryování 1. argumentu
alert(curryovanýSoučet(1)(2)(3) ); // 6,úplné curryování
```

The new `curry`may look complicated, but it's actually easy to understand.
Nová funkce `curry`může vypadat komplikovaně, ale ve skutečnosti je snadné jí porozumět.

The result of`curry(func)`call is the wrapper `curried` that looks like this:
Výsledkem volání`curry(funkce)`je obal `curryovaná`, který vypadá takto:

```js
//func is the function to transform
functioncurried(...args) {
if (args.length >=func.length) { // (1)
returnfunc.apply(this, args);
//funkce je funkce, která se má transformovat
functioncurryovaná(...args) {
if (args.length >=funkce.length) { // (1)
returnfunkce.apply(this, args);
} else {
return function(...args2) { // (2)
returncurried.apply(this, args.concat(args2));
returncurryovaná.apply(this, args.concat(args2));
}
}
};
```

When we run it, there are two`if` execution branches:
Když ji spustíme, obsahuje dvě běhové větve`if`:

1.If passed`args`count is the same or more than the original function has in its definition (`func.length`) , then just pass the call to it using `func.apply`.
2.Otherwise, get a partial: we don't call `func` just yet. Instead, another wrapper is returned, that will re-apply `curried` providing previous arguments together with the new ones.
1.Je-li počet předaných argumentů`args`stejný nebo větší, než v definici původní funkce (`funkce.length`), pak jí jen předáme volání pomocí `funkce.apply`.
2.V opačném případě získáme parciální funkci: ještě funkci `funkce` nebudeme volat. Místo toho se vrátí další obal, který znovu aplikuje funkci `curryovaná` a poskytne jí předchozí argumenty společně s novými.

Then, if we call it, again, we'll get either a new partial (if not enough arguments) or, finally, the result.
Když ji pak znovu zavoláme, získáme buď novou parciální funkci (nemáme-li ještě dost argumentů), nebo nakonec výsledek.

```smart header="Fixed-length functions only"
The currying requires the function to have a fixed number of arguments.
```smart header="Jen pro funkce s pevnou délkou"
Curryování vyžaduje, aby funkce měla pevný počet argumentů.

A function that uses rest parameters, such as`f(...args)`,can't be curried this way.
Funkci, která používá zbytkové parametry, např.`f(...args)`,nelze tímto způsobem curryovat.
```

```smart header="A little more than currying"
By definition, currying should convert `sum(a, b, c)`into `sum(a)(b)(c)`.
```smart header="Víc než jen curryování"
Podle definice by curryování mělo převést `součet(a, b, c)`na `součet(a)(b)(c)`.

But most implementations of currying in JavaScript are advanced, as described: they also keep the function callable in the multi-argument variant.
Většina implementací curryování v JavaScriptu je však pokročilá, jak bylo uvedeno: udržují funkci volatelnou i ve víceargumentové variantě.
```

##Summary
##Shrnutí

*Currying* is a transform that makes `f(a,b,c)`callable as`f(a)(b)(c)`.JavaScript implementations usually both keep the function callable normally and return the partial if the arguments count is not enough.
*Curryování* je transformace, která umožní volat `f(a,b,c)`jako`f(a)(b)(c)`.Implementace v JavaScriptu obvykle současně ponechají funkci volatelnou normálně, ale není-li poskytnuto dost argumentů, vrátí parciální funkci.

Currying allows us to easily get partials. As we've seen in the logging example, after currying the three argument universal function`log(date, importance, message)`gives us partials when called with one argument (like `log(date)`)or two arguments (like `log(date, importance)`).
Curryování nám umožní snadno získat parciální funkci. Jak jsme viděli v příkladu s logováním, univerzální tříargumentová funkce`log(datum, důležitost, zpráva)`nám po curryování vydá parciální funkci, když je volána s jedním argumentem (např. `log(datum)`)nebo se dvěma argumenty (např. `log(datum, důležitost)`).

[8]ページ先頭

©2009-2025 Movatter.jp