You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/99-js-misc/03-currying-partials/article.md
+15-8
Original file line number
Diff line number
Diff line change
@@ -40,7 +40,7 @@ As you can see, the implementation is straightforward: it's just two wrappers.
40
40
41
41
- The result of `curry(func)` is a wrapper `function(a)`.
42
42
- When it is called like `sum(1)`, the argument is saved in the Lexical Environment, and a new wrapper is returned `function(b)`.
43
-
- Then `sum(1)(2)` finally calls `function(b)` providing`2`, and it passes the call to the original multi-argument`sum`.
43
+
- Then this wrapper is called with`2` as an argument, and it passes the call to the original `sum`.
44
44
45
45
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:
46
46
@@ -73,10 +73,15 @@ Let's curry it!
73
73
log =_.curry(log);
74
74
```
75
75
76
-
After that `log` work both the normal way and in the curried form:
76
+
After that `log` work normally:
77
+
78
+
```js
79
+
log(newDate(), "DEBUG", "some debug"); // log(a, b, c)
The new `curry` may look complicated, but it's actually easy to understand.
144
149
145
-
The result of `curry(func)` is the wrapper `curried` that looks like this:
150
+
The result of `curry(func)`call is the wrapper `curried` that looks like this:
146
151
147
152
```js
148
153
// func is the function to transform
@@ -157,7 +162,7 @@ function curried(...args) {
157
162
};
158
163
```
159
164
160
-
When we run it, there are two execution branches:
165
+
When we run it, there are two `if`execution branches:
161
166
162
167
1. Call now: if passed `args` count is the same as the original function has in its definition (`func.length`) or longer, then just pass the call to it.
163
168
2. Get a partial: otherwise, `func` is not called yet. Instead, another wrapper `pass` is returned, that will re-apply `curried` providing previous arguments together with the new ones. Then on a new call, again, we'll get either a new partial (if not enough arguments) or, finally, the result.
@@ -173,7 +178,9 @@ For the call `curried(1)(2)(3)`:
173
178
If that's still not obvious, just trace the calls sequence in your mind or on the paper.
174
179
175
180
```smart header="Fixed-length functions only"
176
-
The currying requires the function to have a known fixed number of arguments.
181
+
The currying requires the function to have a fixed number of arguments.
182
+
183
+
A function that uses rest parameters, such as `f(...args)`, can't be curried this way.
0 commit comments