Skip to content

Commit 23d0816

Browse files
committed
qns: fix issue and regenerate
1 parent 168d103 commit 23d0816

File tree

2 files changed

+69
-59
lines changed
  • questions/provide-some-examples-of-how-currying-and-partial-application-can-be-used

2 files changed

+69
-59
lines changed

README.md

Lines changed: 67 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -601,12 +601,12 @@ For example, let's say we have a `Person` constructor that takes a first name as
601601

602602
```js live
603603
const Person = function (name) {
604-
this.name = name;
604+
this.firstName = name;
605605
this.sayName1 = function () {
606-
console.log(this.name);
606+
console.log(this.firstName);
607607
};
608608
this.sayName2 = () => {
609-
console.log(this.name);
609+
console.log(this.firstName);
610610
};
611611
};
612612

@@ -785,14 +785,16 @@ console.log(namedFunc); // ReferenceError: namedFunc is not defined
785785

786786
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.
787787

788-
```js
788+
```js live
789+
const arr = [-1, 0, 5, 6];
790+
789791
// The filter method is passed an anonymous function.
790-
arr.filter((x) => x > 1);
792+
arr.filter((x) => x > 1); // [5, 6]
791793
```
792794

793795
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.
794796

795-
```js
797+
```js live
796798
// Encapsulating Code
797799
(function () {
798800
// Some code here.
@@ -1127,15 +1129,11 @@ function sum(a, b) {
11271129

11281130
const result = sum(2, 3); // The program waits for sum() to complete before assigning the result
11291131
console.log('Result: ', result); // Output: 5
1130-
1131-
// Console output:
1132-
// Inside sum function
1133-
// Result: 5
11341132
```
11351133

11361134
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).
11371135

1138-
```js
1136+
```js live
11391137
function fetchData(callback) {
11401138
setTimeout(() => {
11411139
const data = { name: 'John', age: 30 };
@@ -1144,16 +1142,12 @@ function fetchData(callback) {
11441142
}
11451143

11461144
console.log('Fetching data...');
1145+
11471146
fetchData((data) => {
11481147
console.log(data); // Output: { name: 'John', age: 30 } (after 2 seconds)
11491148
});
11501149

1151-
console.log('Call made to fetch data'); // Output: This will be printed first
1152-
1153-
// Console output:
1154-
// Fetching data...
1155-
// Call made to fetch data
1156-
// { name: 'John', age: 30 }
1150+
console.log('Call made to fetch data'); // This will print before the data is fetched
11571151
```
11581152

11591153
<!-- Update here: /questions/explain-the-difference-between-synchronous-and-asynchronous-functions/en-US.mdx -->
@@ -2363,7 +2357,7 @@ console.log(greeting); // Output: Hello, John!
23632357

23642358
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:
23652359

2366-
```js
2360+
```js live
23672361
function tag(strings, ...values) {
23682362
return strings[0] + values[0] + strings[1] + values[1] + strings[2];
23692363
}
@@ -3208,14 +3202,16 @@ fetchData(handleData);
32083202

32093203
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.
32103204

3211-
```js
3205+
```js live
3206+
const arr = [-1, 0, 5, 6];
3207+
32123208
// The filter method is passed an anonymous function.
3213-
arr.filter((x) => x > 1);
3209+
arr.filter((x) => x > 1); // [5, 6]
32143210
```
32153211

32163212
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.
32173213

3218-
```js
3214+
```js live
32193215
// Encapsulating Code
32203216
(function () {
32213217
// Some code here.
@@ -3794,15 +3790,11 @@ function sum(a, b) {
37943790

37953791
const result = sum(2, 3); // The program waits for sum() to complete before assigning the result
37963792
console.log('Result: ', result); // Output: 5
3797-
3798-
// Console output:
3799-
// Inside sum function
3800-
// Result: 5
38013793
```
38023794

38033795
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).
38043796

3805-
```js
3797+
```js live
38063798
function fetchData(callback) {
38073799
setTimeout(() => {
38083800
const data = { name: 'John', age: 30 };
@@ -3811,16 +3803,12 @@ function fetchData(callback) {
38113803
}
38123804

38133805
console.log('Fetching data...');
3806+
38143807
fetchData((data) => {
38153808
console.log(data); // Output: { name: 'John', age: 30 } (after 2 seconds)
38163809
});
38173810

3818-
console.log('Call made to fetch data'); // Output: This will be printed first
3819-
3820-
// Console output:
3821-
// Fetching data...
3822-
// Call made to fetch data
3823-
// { name: 'John', age: 30 }
3811+
console.log('Call made to fetch data'); // This will print before the data is fetched
38243812
```
38253813

38263814
<!-- Update here: /questions/explain-the-difference-between-synchronous-and-asynchronous-functions/en-US.mdx -->
@@ -3837,7 +3825,7 @@ console.log('Call made to fetch data'); // Output: This will be printed first
38373825

38383826
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:
38393827

3840-
```js
3828+
```js live
38413829
function fetchData(callback) {
38423830
setTimeout(() => {
38433831
const data = { name: 'John', age: 30 };
@@ -3864,7 +3852,7 @@ fetchData((data) => {
38643852

38653853
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.
38663854

3867-
```js
3855+
```js live
38683856
let promise = new Promise((resolve, reject) => {
38693857
// asynchronous operation
38703858
const success = true;
@@ -3937,7 +3925,7 @@ Promises offer a cleaner alternative to callbacks, helping to avoid callback hel
39373925

39383926
`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.
39393927

3940-
```js
3928+
```js live
39413929
const promise1 = Promise.resolve(3);
39423930
const promise2 = 42;
39433931
const promise3 = new Promise((resolve, reject) => {
@@ -4006,22 +3994,25 @@ fetchData();
40063994

40073995
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:
40083996

4009-
```js
3997+
```js live
40103998
async function fetchData() {
40113999
try {
4000+
// Invalid URl
40124001
const response = await fetch('https://api.example.com/data');
40134002
const data = await response.json();
40144003
console.log(data);
40154004
} catch (error) {
40164005
console.error('Error fetching data:', error);
40174006
}
40184007
}
4008+
4009+
fetchData(); // Error fetching data: ....
40194010
```
40204011

40214012
With Promises, you can use the `.catch()` method:
40224013

4023-
```js
4024-
fetch('https://api.example.com/data')
4014+
```js live
4015+
fetch('https://api.example.com/data') // Invalid URl
40254016
.then((response) => response.json())
40264017
.then((data) => console.log(data))
40274018
.catch((error) => console.error('Error fetching data:', error));
@@ -4353,12 +4344,12 @@ For example, let's say we have a `Person` constructor that takes a first name as
43534344

43544345
```js live
43554346
const Person = function (name) {
4356-
this.name = name;
4347+
this.firstName = name;
43574348
this.sayName1 = function () {
4358-
console.log(this.name);
4349+
console.log(this.firstName);
43594350
};
43604351
this.sayName2 = () => {
4361-
console.log(this.name);
4352+
console.log(this.firstName);
43624353
};
43634354
};
43644355

@@ -5526,14 +5517,12 @@ window.location.replace('https://www.example.com');
55265517

55275518
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:
55285519

5529-
```js live
5520+
```js
55305521
const params = new URLSearchParams(window.location.search);
55315522
const value = params.get('language');
55325523
console.log(value);
55335524
```
55345525

5535-
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'.
5536-
55375526
<!-- Update here: /questions/how-do-you-get-the-query-string-values-of-the-current-page-in-javascript/en-US.mdx -->
55385527

55395528
<br>
@@ -5899,7 +5888,7 @@ try {
58995888

59005889
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:
59015890

5902-
```js
5891+
```js live
59035892
function a() {
59045893
throw new Error('An error occurred');
59055894
}
@@ -5962,7 +5951,7 @@ console.log(result); // Output: 6
59625951

59635952
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.
59645953

5965-
```js
5954+
```js live
59665955
function add(a, b) {
59675956
return a + b;
59685957
}
@@ -5999,13 +5988,17 @@ Currying transforms a function with multiple arguments into a sequence of functi
59995988

60005989
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.
60015990

6002-
```js
6003-
// Currying example
5991+
Currying example:
5992+
5993+
```js live
60045994
const add = (a) => (b) => a + b;
60055995
const addTwo = add(2);
60065996
console.log(addTwo(3)); // 5
5997+
```
5998+
5999+
Partial application example:
60076000

6008-
// Partial application example
6001+
```js live
60096002
const add = (a, b) => a + b;
60106003
const addTwo = add.bind(null, 2);
60116004
console.log(addTwo(3)); // 5
@@ -6111,11 +6104,12 @@ On the other hand, `WeakSet` only allows objects as elements, and these object e
61116104

61126105
To convert a `Set` to an array in JavaScript, you can use the `Array.from()` method or the spread operator. For example:
61136106

6114-
```js
6107+
```js live
61156108
const mySet = new Set([1, 2, 3]);
61166109
const myArray = Array.from(mySet);
6117-
// or
6118-
const myArray = [...mySet];
6110+
// OR const myArray = [...mySet];
6111+
6112+
console.log(myArray); // Output: [1, 2, 3]
61196113
```
61206114

61216115
<!-- Update here: /questions/how-do-you-convert-a-set-to-an-array-in-javascript/en-US.mdx -->
@@ -6197,19 +6191,22 @@ Debouncing and throttling are techniques used to control the rate at which a fun
61976191

61986192
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.
61996193

6200-
```js
6194+
```js live
62016195
function debounce(func, delay) {
62026196
let timeoutId;
62036197
return function (...args) {
62046198
clearTimeout(timeoutId);
62056199
timeoutId = setTimeout(() => func.apply(this, args), delay);
62066200
};
62076201
}
6202+
6203+
const debouncedHello = debounce(() => console.log('Hello world!'), 2000);
6204+
debouncedHello(); // Prints 'Hello world!' after 2 seconds
62086205
```
62096206

62106207
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.
62116208

6212-
```js
6209+
```js live
62136210
function throttle(func, limit) {
62146211
let inThrottle;
62156212
return function (...args) {
@@ -6220,6 +6217,17 @@ function throttle(func, limit) {
62206217
}
62216218
};
62226219
}
6220+
6221+
const handleResize = throttle(() => {
6222+
// Update element positions
6223+
console.log('Window resized at', new Date().toLocaleTimeString());
6224+
}, 2000);
6225+
6226+
// Simulate rapid calls to handleResize every 100ms
6227+
let intervalId = setInterval(() => {
6228+
handleResize();
6229+
}, 100);
6230+
// 'Window resized' is outputted only every 2 seconds due to throttling
62236231
```
62246232

62256233
<!-- Update here: /questions/explain-the-concept-of-debouncing-and-throttling/en-US.mdx -->
@@ -6708,7 +6716,7 @@ console.log(myCarWithGPS.drive()); // "Driving with GPS"
67086716

67096717
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.
67106718

6711-
```js
6719+
```js live
67126720
class Context {
67136721
constructor(strategy) {
67146722
this.strategy = strategy;
@@ -6722,18 +6730,20 @@ class Context {
67226730
class ConcreteStrategyA {
67236731
doAlgorithm(data) {
67246732
// Implementation of algorithm A
6733+
return 'Algorithm A was run on ' + data;
67256734
}
67266735
}
67276736

67286737
class ConcreteStrategyB {
67296738
doAlgorithm(data) {
67306739
// Implementation of algorithm B
6740+
return 'Algorithm B was run on ' + data;
67316741
}
67326742
}
67336743

67346744
// Usage
67356745
const context = new Context(new ConcreteStrategyA());
6736-
context.executeStrategy(data);
6746+
context.executeStrategy('someData'); // Output: Algorithm A was run on someData
67376747
```
67386748

67396749
<!-- Update here: /questions/explain-the-concept-of-the-strategy-pattern/en-US.mdx -->
@@ -6750,7 +6760,7 @@ context.executeStrategy(data);
67506760

67516761
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.
67526762

6753-
```js
6763+
```js live
67546764
class Command {
67556765
execute() {}
67566766
undo() {}

questions/provide-some-examples-of-how-currying-and-partial-application-can-be-used/en-US.mdx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,15 @@ title: Provide some examples of how currying and partial application can be used
66

77
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.
88

9-
### Currying example
9+
Currying example:
1010

1111
```js live
1212
const add = (a) => (b) => a + b;
1313
const addTwo = add(2);
1414
console.log(addTwo(3)); // 5
1515
```
1616

17-
### Partial application example
17+
Partial application example:
1818

1919
```js live
2020
const add = (a, b) => a + b;

0 commit comments

Comments
 (0)