Skip to content

Commit a1a24c7

Browse files
2 parents 01bfc4b + 265390e commit a1a24c7

File tree

9 files changed

+1627
-1
lines changed

9 files changed

+1627
-1
lines changed

HigherOrderFunction/filter.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Filter function
2+
// Filter function is basically used to filter the value inside an array. The arr.filter() method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method.
3+
4+
const arr = [5, 1, 3, 2, 6];
5+
// filter odd values
6+
function isOdd(x) {
7+
return x % 2;
8+
}
9+
const oddArr = arr.filter(isOdd); // [5,1,3]
10+
console.log(oddArr); // Output: [5, 1, 3]
11+
// Other way of writing the above:
12+
const oddArrAlt = arr.filter((x) => x % 2);
13+
console.log(oddArrAlt); // Output: [5, 1, 3]
14+
15+
//pollyfill for filter
16+
Array.prototype.myFilter = function(callback) {
17+
let result = [];
18+
for (let i = 0; i < this.length; i++) {
19+
if (callback(this[i], i, this)) { // Pass current element, index, and array to the callback
20+
result.push(this[i]);
21+
}
22+
}
23+
return result;
24+
}
25+
function isEven(x){
26+
return x % 2 === 0 ;
27+
}
28+
const myEvenArr = arr.myFilter(isEven);
29+
console.log(myEvenArr); // Output: [ 2, 6 ]
30+

HigherOrderFunction/hof.js

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
2+
// Higher Order Functions in JavaScript
3+
4+
// 1. What is a Higher Order Function?
5+
// A higher order function is a function that either takes one or more functions as arguments, or returns a function as its result.
6+
7+
// Example 1: Passing a function as an argument
8+
function greet(name) {
9+
return `Hello, ${name}!`;
10+
}
11+
12+
function processUserInput(callback) {
13+
const name = 'Aditya';
14+
return callback(name);
15+
}
16+
17+
console.log(processUserInput(greet)); // Output: Hello, Aditya!
18+
19+
// Example 2: Returning a function
20+
function multiplier(factor) {
21+
return function(number) {
22+
return number * factor;
23+
};
24+
}
25+
26+
const double = multiplier(2);
27+
console.log(double); // Output: [Function: anonymous]
28+
// Using the returned function
29+
console.log(double(5)); // Output: 10
30+
31+
// 2. Why use Higher Order Functions?
32+
// - Abstraction: Hide details and expose only necessary parts.
33+
// - Reusability: Write generic functions that work with other functions.
34+
// - Functional Programming: Enables techniques like map, filter, reduce.
35+
36+
// 3. Built-in Higher Order Functions
37+
const numbers = [1, 2, 3, 4, 5];
38+
39+
// map: transforms each element
40+
const squares = numbers.map(x => x * x);
41+
console.log(squares); // [1, 4, 9, 16, 25]
42+
43+
// filter: selects elements based on condition
44+
const evens = numbers.filter(x => x % 2 === 0);
45+
console.log(evens); // [2, 4]
46+
47+
// reduce: accumulates values
48+
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
49+
console.log(sum); // 15
50+
51+
// 4. Custom Higher Order Function Example
52+
function repeat(n, action) {
53+
for (let i = 0; i < n; i++) {
54+
action(i);
55+
}
56+
}
57+
58+
repeat(3, console.log); // Logs 0, 1, 2
59+
60+
// 5. Returning Functions (Closures)
61+
function makeCounter() {
62+
let count = 0;
63+
return function() {
64+
count++;
65+
return count;
66+
};
67+
}
68+
69+
const counter = makeCounter();
70+
console.log(counter()); // 1
71+
console.log(counter()); // 2
72+
73+
// 6. Practical Example: Function Composition
74+
function compose(f, g) {
75+
return function(x) {
76+
return f(g(x));
77+
};
78+
}
79+
80+
const add1 = x => x + 1;
81+
const times2 = x => x * 2;
82+
const add1ThenTimes2 = compose(times2, add1);
83+
console.log(add1ThenTimes2(5)); // (5 + 1) * 2 = 12
84+
85+
86+
const radius = [1, 2, 3, 4];
87+
const calculateArea = function (radius) {
88+
const output = [];
89+
for (let i = 0; i < radius.length; i++) {
90+
output.push(Math.PI * radius[i] * radius[i]);
91+
}
92+
return output;
93+
};
94+
console.log(calculateArea(radius));
95+
96+
const calculateCircumference = function (radius) {
97+
const output = [];
98+
for (let i = 0; i < radius.length; i++) {
99+
output.push(2 * Math.PI * radius[i]);
100+
}
101+
return output;
102+
};
103+
console.log(calculateCircumference(radius));
104+
105+
const radiusArr = [1, 2, 3, 4];
106+
107+
// logic to calculate area
108+
const area = function (radius) {
109+
return Math.PI * radius * radius;
110+
}
111+
112+
// logic to calculate circumference
113+
const circumference = function (radius) {
114+
return 2 * Math.PI * radius;
115+
}
116+
117+
const calculate = function(radiusArr, operation) {
118+
const output = [];
119+
for (let i = 0; i < radiusArr.length; i++) {
120+
output.push(operation(radiusArr[i]));
121+
}
122+
return output;
123+
}
124+
console.log(calculate(radiusArr, area));
125+
console.log(calculate(radiusArr, circumference));
126+
// Over here calculate is HOF
127+
// Over here we have extracted logic into separate functions. This is the beauty of functional programming.
128+
// We can also use built-in higher order functions like map to achieve the same result
129+
const areas = radiusArr.map(area);
130+
console.log(areas);
131+
const circumferences = radiusArr.map(circumference);
132+
console.log(circumferences);
133+
134+
135+

HigherOrderFunction/map.js

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
2+
const arr = [1, 2, 3, 4, 5];
3+
4+
function double(x){
5+
return x * 2;
6+
}
7+
8+
function triple(x){
9+
return x * 3;
10+
}
11+
12+
const outputDouble = arr.map(double);
13+
console.log(outputDouble); // [2, 4, 6, 8, 10]
14+
// alernate way to use map
15+
16+
const outputDoubleAlt = arr.map(function(x) { // Using a regular function
17+
return x * 2;
18+
});
19+
// This is equivalent to the previous example
20+
// It uses a regular function instead of an arrow function
21+
22+
console.log(outputDoubleAlt); // [2, 4, 6, 8, 10]
23+
24+
const outputDoubleAltArrow = arr.map(x => x * 2);
25+
console.log(outputDoubleAltArrow); // [2, 4, 6, 8, 10]
26+
27+
const outputTriple = arr.map(triple);
28+
console.log(outputTriple); // [3, 6, 9, 12, 15]
29+
30+
function binary(x) {
31+
return x.toString(2);
32+
}
33+
const binaryArr = arr.map(binary);
34+
35+
// The above code can be rewritten as :
36+
const binaryArr1 = arr.map(function binary(x) {
37+
return x.toString(2);
38+
});
39+
40+
// OR -> Arrow function
41+
const binaryArr2 = arr.map((x) => x.toString(2));
42+
43+
const users = [
44+
{ firstName: "Aditya", lastName: "Kumar", age: 23 },
45+
{ firstName: "Ashish", lastName: "Kumar", age: 29 },
46+
{ firstName: "Ankit", lastName: "Roy", age: 29 },
47+
{ firstName: "Pranav", lastName: "Mukherjee", age: 50 },
48+
];
49+
const fullNameArray = users.map(x => {
50+
return x.firstName + " " + x.lastName;
51+
})
52+
console.log(fullNameArray);
53+
54+
// Polifill for map
55+
Array.prototype.myMap = function(callback) {
56+
let result = [];
57+
for (let i = 0; i < this.length; i++) {
58+
result.push(callback(this[i], i, this)); // Pass current element, index, and array to the callback
59+
}
60+
return result;
61+
};
62+
// This is a custom implementation of the map function that mimics the behavior of Array.prototype.map
63+
// It iterates over the array, applies the callback function to each element, and returns a new array with the results.
64+
// The callback function can take three arguments: the current element, its index, and the array
65+
// This allows for more flexibility in how the callback is used, similar to the built-in map
66+
// This custom implementation can be used in the same way as the built-in map function, allowing
67+
// developers to use it in their code without relying on the built-in method.
68+
// This is useful for environments where the built-in map function is not available or for educational purposes
69+
// Usage:
70+
console.log(arr.myMap(x => x * 200)); // [2, 4, 6]
71+
72+
73+

0 commit comments

Comments
 (0)