-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhighOrderFunctions.js
72 lines (70 loc) · 1.65 KB
/
highOrderFunctions.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
//--------------forEach---------------------//
function myForEach(callback,optionalObject){
if(optionalObject) {
callback = callback.bind(optionalObject);
}
for(let i=0;i<this.length;i++) {
callback(this[i],i,this)
}
}
Array.prototype.myForEach = myForEach;
//******Tests*******
//Test 1
const arr = [1,2,3];
arr.myForEach(num => console.log(num));
//*Print on screen 1 2 3*
-----------------------
//Test 2 (with optional argument this -> test from mdn)
function Counter() {
this.sum = 0;
this.count = 0;
}
Counter.prototype.add = function(array) {
array.myForEach(function(entry) {
this.sum += entry;
++this.count;
}, this);
// ^---- Note
};
const obj = new Counter();
obj.add([2, 5, 9]);
obj.count;
// 3
obj.sum;
//16
//--------------Filter---------------------//
function myFilter(callback,optionalObject){
let filteredArr =[];
if(optionalObject){
callback=callback.bind(optionalObject);
}
for(let i=0;i<this.length;i++){
if (callback(this[i],i,this)){
filteredArr.push(this[i])
}
}
return filteredArr;
}
Array.prototype.myFilter = myfilter;
//******Tests*******
//Test 1
const arr = [1,2,3];
const myFilteredArray = arr.myFilter(num => num>=2);
console.log(myFilteredArray);
//*Print on screen [2,3]
//-------------map---------------------//
function mymap(callback,optionalObject){
let mappedArray =[];
if(optionalObject){
callback=callback.bind(optionalObject);
}
for(let i=0;i<this.length;i++){
mappedArray.push(callback(this[i],i,this))
}
return mappedArray;
}
//Test 1
const arr = [1,2,3];
const myMappedArr = arr.myFilter(num => num + 10);
console.log(myMappedArr);
//*Print on screen [11,12,13]