-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhigher-order-functions.js
More file actions
74 lines (53 loc) · 1.68 KB
/
higher-order-functions.js
File metadata and controls
74 lines (53 loc) · 1.68 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* A function that takes another function as an argument or a function that gives another function as an output is called Higher Order Functions.
*/
function x(fn) {
fn();
}
function y() {
console.log("Hello World!");
}
x(y);
/**
* x is called higher Order function
* y is called callback function
*/
const data = [10, 23, 89, 53, 76, 89];
const calculateSquare = (arr) => {
const output = [];
for (let i = 0; i < arr.length; i++) {
output.push(Math.pow(arr[i], 2));
}
return output;
}
const multiplyBy7 = (arr) => {
const output = [];
for (let j = 0; j < arr.length; j++) {
output.push(arr[j] * 7);
}
return output;
}
console.log(calculateSquare(data)); // [ 100, 529, 7921, 2809, 5776, 7921 ]
console.log(multiplyBy7(data)); // [ 70, 161, 623, 371, 532, 623 ]
// Using Higher Order Functions
const calSubtract = (arrEle) => arrEle - 10;
const calculateSubtraction = (arr, calcFn) => {
const output = [];
for (var i = 0; i < arr.length; i++) {
output.push(calcFn(arr[i]))
}
return output;
}
console.log(calculateSubtraction(data, calSubtract)); //[ 0, 13, 79, 43, 66, 79 ]
console.log(data.map(calSubtract)); //[ 0, 13, 79, 43, 66, 79 ]
// Prototype is a global constructor which allows you to add new properties and method to the array.
const calcRem = (ele) => ele % 10;
Array.prototype.calculateRemainder = function (calcRem) {
let output = [];
for (let i = 0; i < this.length; i++) {
output.push(calcRem(this[i]));
}
return output;
}
console.log(data.calculateRemainder(calcRem)); //[ 0, 3, 9, 3, 6, 9 ]
console.log(data.map(calSubtract)); // Here Map acts as a higher order function