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

Commit 891139b

Browse files
authored
Create myReduce.md
1 parent 4a9ec03 commit 891139b

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

‎FE75/myReduce.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
```js
2+
Array.prototype.myReduce = function (callbackFn, initialValue) {
3+
if (typeof callbackFn !== 'function') {
4+
throw new TypeError(callbackFn + ' is not a function');
5+
}
6+
7+
const arr = this; // `this` refers to the array on which myReduce is called
8+
let accumulator = initialValue; // Initialize the accumulator
9+
let startIndex = 0; // Starting index for iteration
10+
11+
// If initialValue is not provided, use the first element as the initial value
12+
if (accumulator === undefined) {
13+
if (arr.length === 0) {
14+
throw new TypeError('Reduce of empty array with no initial value');
15+
}
16+
accumulator = arr[0];
17+
startIndex = 1; // Skip the first element since it's now the accumulator
18+
}
19+
20+
// Iterate through the array elements and apply the callback function
21+
for (let i = startIndex; i < arr.length; i++) {
22+
accumulator = callbackFn(accumulator, arr[i], i, arr);
23+
}
24+
25+
return accumulator; // Return the accumulated value
26+
};
27+
```
28+
### Explanation
29+
Check if callbackFn is a function: We first check if the provided callbackFn is a valid function. If not, we throw a TypeError.
30+
31+
#### Handle initialValue:
32+
33+
* If initialValue is provided, we use it to initialize the accumulator.
34+
* If no initialValue is provided, we take the first element of the array (arr[0]) as the accumulator.
35+
* However, if the array is empty and no initialValue is provided, we throw a TypeError.
36+
37+
#### Iterate over the array: We use a for loop to iterate over the elements of the array starting at startIndex. For each element, we call the callbackFn with the following arguments:
38+
39+
* accumulator (the accumulated value so far),
40+
* the current element (arr[i]),
41+
* the current index (i),
42+
* the entire array (arr).
43+
44+
#### Update the accumulator: The result of the callbackFn is assigned back to the accumulator.
45+
46+
#### Return the result: Finally, we return the accumulated value (accumulator).

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /