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: README.md
+67-57Lines changed: 67 additions & 57 deletions
Original file line number
Diff line number
Diff line change
@@ -601,12 +601,12 @@ For example, let's say we have a `Person` constructor that takes a first name as
601
601
602
602
```js live
603
603
constPerson=function (name) {
604
-
this.name= name;
604
+
this.firstName= name;
605
605
this.sayName1=function () {
606
-
console.log(this.name);
606
+
console.log(this.firstName);
607
607
};
608
608
this.sayName2= () => {
609
-
console.log(this.name);
609
+
console.log(this.firstName);
610
610
};
611
611
};
612
612
@@ -785,14 +785,16 @@ console.log(namedFunc); // ReferenceError: namedFunc is not defined
785
785
786
786
Anonymous function in Javascript is a function that does not have any name associated with it. They are typically used as arguments to other functions or assigned to variables.
787
787
788
-
```js
788
+
```js live
789
+
constarr= [-1, 0, 5, 6];
790
+
789
791
// The filter method is passed an anonymous function.
790
-
arr.filter((x) => x >1);
792
+
arr.filter((x) => x >1);// [5, 6]
791
793
```
792
794
793
795
They are often used as arguments to other functions, known as higher-order functions, which can take functions as input and return a function as output. Anonymous functions can access variables from the outer scope, a concept known as closures, allowing them to "close over" and remember the environment in which they were created.
794
796
795
-
```js
797
+
```js live
796
798
// Encapsulating Code
797
799
(function () {
798
800
// Some code here.
@@ -1127,15 +1129,11 @@ function sum(a, b) {
1127
1129
1128
1130
constresult=sum(2, 3); // The program waits for sum() to complete before assigning the result
1129
1131
console.log('Result: ', result); // Output: 5
1130
-
1131
-
// Console output:
1132
-
// Inside sum function
1133
-
// Result: 5
1134
1132
```
1135
1133
1136
1134
Asynchronous functions usually accept a callback as a parameter and execution continue on to the next line immediately after the asynchronous function is invoked. The callback is only invoked when the asynchronous operation is complete and the call stack is empty. Heavy duty operations such as loading data from a web server or querying a database should be done asynchronously so that the main thread can continue executing other operations instead of blocking until that long operation to complete (in the case of browsers, the UI will freeze).
1137
1135
1138
-
```js
1136
+
```js live
1139
1137
functionfetchData(callback) {
1140
1138
setTimeout(() => {
1141
1139
constdata= { name:'John', age:30 };
@@ -1144,16 +1142,12 @@ function fetchData(callback) {
Tagged templates in JavaScript allow you to parse template literals with a function. The function receives the literal strings and the values as arguments, enabling custom processing of the template. For example:
Anonymous function in Javascript is a function that does not have any name associated with it. They are typically used as arguments to other functions or assigned to variables.
3210
3204
3211
-
```js
3205
+
```js live
3206
+
constarr= [-1, 0, 5, 6];
3207
+
3212
3208
// The filter method is passed an anonymous function.
3213
-
arr.filter((x) => x >1);
3209
+
arr.filter((x) => x >1);// [5, 6]
3214
3210
```
3215
3211
3216
3212
They are often used as arguments to other functions, known as higher-order functions, which can take functions as input and return a function as output. Anonymous functions can access variables from the outer scope, a concept known as closures, allowing them to "close over" and remember the environment in which they were created.
3217
3213
3218
-
```js
3214
+
```js live
3219
3215
// Encapsulating Code
3220
3216
(function () {
3221
3217
// Some code here.
@@ -3794,15 +3790,11 @@ function sum(a, b) {
3794
3790
3795
3791
constresult=sum(2, 3); // The program waits for sum() to complete before assigning the result
3796
3792
console.log('Result: ', result); // Output: 5
3797
-
3798
-
// Console output:
3799
-
// Inside sum function
3800
-
// Result: 5
3801
3793
```
3802
3794
3803
3795
Asynchronous functions usually accept a callback as a parameter and execution continue on to the next line immediately after the asynchronous function is invoked. The callback is only invoked when the asynchronous operation is complete and the call stack is empty. Heavy duty operations such as loading data from a web server or querying a database should be done asynchronously so that the main thread can continue executing other operations instead of blocking until that long operation to complete (in the case of browsers, the UI will freeze).
3804
3796
3805
-
```js
3797
+
```js live
3806
3798
functionfetchData(callback) {
3807
3799
setTimeout(() => {
3808
3800
constdata= { name:'John', age:30 };
@@ -3811,16 +3803,12 @@ function fetchData(callback) {
@@ -3837,7 +3825,7 @@ console.log('Call made to fetch data'); // Output: This will be printed first
3837
3825
3838
3826
A callback function is a function passed as an argument to another function, which is then invoked inside the outer function to complete some kind of routine or action. In asynchronous operations, callbacks are used to handle tasks that take time to complete, such as network requests or file I/O, without blocking the execution of the rest of the code. For example:
3839
3827
3840
-
```js
3828
+
```js live
3841
3829
functionfetchData(callback) {
3842
3830
setTimeout(() => {
3843
3831
constdata= { name:'John', age:30 };
@@ -3864,7 +3852,7 @@ fetchData((data) => {
3864
3852
3865
3853
Promises in JavaScript are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They have three states: `pending`, `fulfilled`, and `rejected`. You can handle the results of a promise using the `.then()` method for success and the `.catch()` method for errors.
3866
3854
3867
-
```js
3855
+
```js live
3868
3856
let promise =newPromise((resolve, reject) => {
3869
3857
// asynchronous operation
3870
3858
constsuccess=true;
@@ -3937,7 +3925,7 @@ Promises offer a cleaner alternative to callbacks, helping to avoid callback hel
3937
3925
3938
3926
`Promise.all()` is a method in JavaScript that takes an array of promises and returns a single promise. This returned promise resolves when all the input promises have resolved, or it rejects if any of the input promises reject. It is useful for running multiple asynchronous operations in parallel and waiting for all of them to complete.
3939
3927
3940
-
```js
3928
+
```js live
3941
3929
constpromise1=Promise.resolve(3);
3942
3930
constpromise2=42;
3943
3931
constpromise3=newPromise((resolve, reject) => {
@@ -4006,22 +3994,25 @@ fetchData();
4006
3994
4007
3995
To handle errors in asynchronous operations, you can use `try...catch` blocks with `async/await` syntax or `.catch()` method with Promises. For example, with `async/await`, you can wrap your code in a `try...catch` block to catch any errors:
To get the query string values of the current page in JavaScript, you can use the `URLSearchParams` object. First, create a `URLSearchParams` instance with `window.location.search`, then use the `get` method to retrieve specific query parameters. For example:
This will give you the value of the query parameter named `language`. If you look at the URL of this page, you can see that the `language` parameter is set to 'js'.
Error propagation in JavaScript refers to how errors are passed through the call stack. When an error occurs in a function, it can be caught and handled using `try...catch` blocks. If not caught, the error propagates up the call stack until it is either caught or causes the program to terminate. For example:
Partial application is a technique in functional programming where a function is applied to some of its arguments, producing a new function that takes the remaining arguments. This allows you to create more specific functions from general ones. For example, if you have a function `add(a, b)`, you can partially apply it to create a new function `add5` that always adds 5 to its argument.
5964
5953
5965
-
```js
5954
+
```js live
5966
5955
functionadd(a, b) {
5967
5956
return a + b;
5968
5957
}
@@ -5999,13 +5988,17 @@ Currying transforms a function with multiple arguments into a sequence of functi
5999
5988
6000
5989
Currying transforms a function with multiple arguments into a sequence of functions, each taking a single argument. Partial application fixes a few arguments of a function, producing another function with a smaller number of arguments. For example, currying a function `add(a, b)` would look like `add(a)(b)`, while partial application of `add(2, b)` would fix the first argument to 2, resulting in a function that only needs the second argument.
6001
5990
6002
-
```js
6003
-
// Currying example
5991
+
Currying example:
5992
+
5993
+
```js live
6004
5994
constadd= (a) => (b) => a + b;
6005
5995
constaddTwo=add(2);
6006
5996
console.log(addTwo(3)); // 5
5997
+
```
5998
+
5999
+
Partial application example:
6007
6000
6008
-
// Partial application example
6001
+
```js live
6009
6002
constadd= (a, b) => a + b;
6010
6003
constaddTwo=add.bind(null, 2);
6011
6004
console.log(addTwo(3)); // 5
@@ -6111,11 +6104,12 @@ On the other hand, `WeakSet` only allows objects as elements, and these object e
6111
6104
6112
6105
To convert a `Set` to an array in JavaScript, you can use the `Array.from()` method or the spread operator. For example:
@@ -6197,19 +6191,22 @@ Debouncing and throttling are techniques used to control the rate at which a fun
6197
6191
6198
6192
Debouncing delays the execution of a function until a certain amount of time has passed since it was last called. This is useful for scenarios like search input fields where you want to wait until the user has stopped typing before making an API call.
debouncedHello(); // Prints 'Hello world!' after 2 seconds
6208
6205
```
6209
6206
6210
6207
Throttling ensures that a function is called at most once in a specified time interval. This is useful for scenarios like window resizing or scrolling where you want to limit the number of times a function is called.
6211
6208
6212
-
```js
6209
+
```js live
6213
6210
functionthrottle(func, limit) {
6214
6211
let inThrottle;
6215
6212
returnfunction (...args) {
@@ -6220,6 +6217,17 @@ function throttle(func, limit) {
@@ -6708,7 +6716,7 @@ console.log(myCarWithGPS.drive()); // "Driving with GPS"
6708
6716
6709
6717
The Strategy pattern is a behavioral design pattern that allows you to define a family of algorithms, encapsulate each one as a separate class, and make them interchangeable. This pattern lets the algorithm vary independently from the clients that use it. For example, if you have different sorting algorithms, you can define each one as a strategy and switch between them without changing the client code.
6710
6718
6711
-
```js
6719
+
```js live
6712
6720
classContext {
6713
6721
constructor(strategy) {
6714
6722
this.strategy= strategy;
@@ -6722,18 +6730,20 @@ class Context {
6722
6730
classConcreteStrategyA {
6723
6731
doAlgorithm(data) {
6724
6732
// Implementation of algorithm A
6733
+
return'Algorithm A was run on '+ data;
6725
6734
}
6726
6735
}
6727
6736
6728
6737
classConcreteStrategyB {
6729
6738
doAlgorithm(data) {
6730
6739
// Implementation of algorithm B
6740
+
return'Algorithm B was run on '+ data;
6731
6741
}
6732
6742
}
6733
6743
6734
6744
// Usage
6735
6745
constcontext=newContext(newConcreteStrategyA());
6736
-
context.executeStrategy(data);
6746
+
context.executeStrategy('someData'); // Output: Algorithm A was run on someData
The Command pattern is a behavioral design pattern that turns a request into a stand-alone object containing all information about the request. This transformation allows for parameterization of methods with different requests, queuing of requests, and logging of the requests. It also supports undoable operations. In JavaScript, it can be implemented by creating command objects with `execute` and `undo` methods.
Copy file name to clipboardExpand all lines: questions/provide-some-examples-of-how-currying-and-partial-application-can-be-used/en-US.mdx
+2-2Lines changed: 2 additions & 2 deletions
Original file line number
Diff line number
Diff line change
@@ -6,15 +6,15 @@ title: Provide some examples of how currying and partial application can be used
6
6
7
7
Currying transforms a function with multiple arguments into a sequence of functions, each taking a single argument. Partial application fixes a few arguments of a function, producing another function with a smaller number of arguments. For example, currying a function `add(a, b)` would look like `add(a)(b)`, while partial application of `add(2, b)` would fix the first argument to 2, resulting in a function that only needs the second argument.
0 commit comments