-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhighOrder.js
100 lines (90 loc) · 2.21 KB
/
highOrder.js
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* forEach
*/
Array.prototype.forEach = function (fn, context) {
for (let k = 0, length = this.length; k < length; k++) {
if (typeof fn === 'function' && Object.prototype.hasOwnProperty.call(this, k)) {
fn.call(context, this[k], k, this)
}
}
}
/**
* map
*/
Array.prototype.map = function (fn, context) {
let arr = []
if (typeof fn === 'function') {
for (let k = 0, length = this.length; k < length; k++) {
arr.push(fn.call(context, this[k], k, this))
}
}
return arr
}
/**
* filter
*/
Array.prototype.filter = function (fn, context) {
let arr = []
if (typeof fn === 'function') {
for (let k = 0, length = this.length; k < length; k++) {
fn.call(context, this[k], k, this) && arr.push(this[k])
}
}
return arr
}
/**
* some
*/
Array.prototype.some = function (fn, context) {
let passed = false
if (typeof fn === 'function') {
for (let k = 0, length = this.length; k < length; k++) {
if (passed === true) break;
passed = !!fn.call(context, this[k], k, this)
}
}
return passed
}
/**
* every
*/
Array.prototype.every = function (fn, context) {
let passed = true
if (typeof fn === 'function') {
for (let k = 0, length = this.length; k < length; k++) {
if (passed === false) break;
passed = !!fn.call(context, this[k], k, this)
}
}
return passed
}
/**
* indexof
*/
Array.prototype.indexOf = function (searchElment, fromIndex) {
let index = -1;
fromIndex = fromIndex * 1 || 0
for (k = 0, length = this.length; k < length; k++) {
if (k >= fromIndex && this[k] === searchElment) {
index = k
break
}
}
return index
}
/**
* reduce
*/
Array.prototype.reduce = function (callback, initialValue) {
let previous = initialValue, k = 0, length = this.length
if (typeof initialValue === undefined) {
previous = this[0]
k = 1
}
if (typeof callback === 'function') {
for (k; k < length; k++) {
this.hasOwnProperty(k) && (previous = callback(previous, this[k], k, this))
}
}
return previous
}