-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.reduce.js
More file actions
40 lines (34 loc) · 1.03 KB
/
array.reduce.js
File metadata and controls
40 lines (34 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* @param {Function} callback
* @param {*} initialValue
*/
Array.prototype._reduce = function (callback, initialValue) {
if (typeof callback !== 'function') {
throw new TypeError(callback + 'is not a function')
}
const array = Object(this)
const len = array.length
let index = 0
let accumulator
if (arguments.length > 1) {
accumulator = initialValue
} else {
// 将原数组转换为普通对象配合 in 操作符来跳过空元素。
// 取数组第一个非空元素作为 initialValue。
while (index < len && !(index in array)) {
index++
}
// if len is 0 and initialValue is not present
if (index >= len) {
throw new TypeError('Reduce of empty array without initial value')
}
accumulator = array[index++]
}
while (index < len) {
if (index in array) {
accumulator = callback(accumulator, array[index], index, array)
}
index++
}
return accumulator
}