-
Notifications
You must be signed in to change notification settings - Fork 0
/
array-methods-polyfill.js
71 lines (61 loc) · 1.86 KB
/
array-methods-polyfill.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
Array.prototype.myMap = function (callback) {
const output = [];
for(let i = 0; i < this.length; i++) {
output.push(callback(this[i],i,this));
}
return output;
};
Array.prototype.myMap = function (callbackFn, thisArg) {
const output = [];
for (let i = 0; i < this.length; i++) {
if (Object.hasOwn(this, i)) {
output[i] = callbackFn.call(thisArg, this[i], i, this);
}
}
return output;
};
Array.prototype.myFilter = function (callback) {
const output = [];
for(let i = 0; i < this.length; i++) {
if(callback(this[i],i,this) === true) {
output.push(this[i]);
}
}
return output;
};
Array.prototype.myFilter = function (callbackFn, thisArg) {
const output = [];
for(let i = 0; i < this.length; i++) {
if(Object.hasOwn(this,i) && callbackFn.call(thisArg,this[i],i,this) === true) {
output.push(this[i]);
}
}
return output;
};
Array.prototype.myReduce = function (callback, initialValue) {
let accumulator = initialValue;
for(let i = 0; i <this.length; i++) {
if(i === 0 && initialValue === undefined) {
accumulator = this[i];
} else {
accumulator = callback(accumulator, this[i], i, this);
}
}
return accumulator;
};
Array.prototype.myReduce = function (callbackFn, initialValue) {
let accumulator = initialValue;
if (initialValue === undefined && this.length === 0) {
throw new TypeError('Reduce of empty array with no initial value');
}
for(let i = 0; i <this.length; i++) {
if(i === 0 && initialValue === undefined) {
accumulator = this[i];
} else {
if(Object.hasOwn(this, i)) {
accumulator = callbackFn(accumulator, this[i], i, this);
}
}
}
return accumulator;
};