-
Notifications
You must be signed in to change notification settings - Fork 1
/
14 Functional Programming .js
83 lines (69 loc) · 1.93 KB
/
14 Functional Programming .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
//Basic example of higher order function
function x() {
console.log("Akshad");
}
function y(x) {
}
//Normally used method to calculate area and circumferenece
const radius = [1, 2, 3, 4, 5];
const calculateArea = function (radius) {
const output = [];
for (let i = 0; i < radius.length; i++) {
output.push(Math.PI * radius[i] * radius[i]);
}
return output;
}
console.log(calculateArea(radius));
//circumference normal
const circumfereneceOfCircle = function (radius) {
const output = [];
for (let i = 0; i < radius.length; i++) {
output.push(2 * Math.PI * radius[i])
}
return output;
}
console.log(circumfereneceOfCircle(radius));
//for diameter
const diameterOfCircle = function (radius) {
const output = [];
for (let i = 0; i < radius.length; i++) {
output.push(2 * radius[i])
}
return output;
}
console.log(diameterOfCircle(radius));
///By functional programming using generic function
const area = function (radius) {
return Math.PI * radius * radius;
}
const circumeference = function (radius) {
return 2 * Math.PI * radius;
}
const diameter = function (radius) {
return 2 * radius;
}
const calculate = function (radius, logic) {
const output = [];
for (let i = 0; i < radius.length; i++) {
output.push(logic(radius[i]))
}
return output;
}
// console.log(calculate(radius, area));
// console.log(calculate(radius, circumeference));
// console.log(calculate(radius, diameter));
// Map function // although it is same as above function
console.log(radius.map(area));
console.log(radius.map(circumeference));
console.log(radius.map(diameter));
//Polyfill for map function
Array.prototype.calculate = function (logic) {
const output = [];
for (let i = 0; i < this.length; i++) {
output.push(logic(this[i]))
}
return output;
}
// Map function
console.log(radius.calculate(area));
console.log(radius.calculate(circumeference));