-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomMap.js
More file actions
56 lines (39 loc) · 1.39 KB
/
Copy pathCustomMap.js
File metadata and controls
56 lines (39 loc) · 1.39 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Q. you need to make your own customMap method
// Array.prototype - this is Javascript way of saying
// "Hey i want to add a brand new method or tool to every single array
// that ever gets created by atteching the customMap to the prototype
// and any array can now use it" like [2,3,6,7].customMap(...).
// thisArg is optional helper. if we want to our callback function to use
// a specific this context inside it. then we pass it
// (Most people don't use this often, but the official JavaScript spec requires it!).
Array.prototype.customMap = function (callback, thisArg) {
let result = [];
for (let i = 0; i < this.length; i++) {
if (i in this) {
result[i] = callback.call(thisArg, this[i], i, this);
}
}
return result
}
let nums = [2, 4, 6, 8];
let squareArr = nums.customMap((e) => {
return e ** 2;
})
console.log(squareArr);
// Create a CustomFilter method that works actual like Array.filter() method
Array.prototype.customFilter = function (callback, thisArg) {
let filtereArr = [];
for (let i = 0; i < this.length; i++) {
if (i in this) {
let passed = callback.call(thisArg, this[i], i, this);
if (passed) {
filtereArr.push(this[i])
}
}
}
return filtereArr;
}
let filteredArr = nums.customFilter((ele) => {
return ele > 5;
})
console.log(filteredArr);