-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0_filter.js
73 lines (59 loc) · 2.62 KB
/
0_filter.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
/*
* **Higher-Order Functions**
* If functions accept function parameters and are able to return functions
* values then the functions are higher order functions. In javascript,
* functions are higher order function.
*/
(
function()
// Anonymous function inside a bracket which lets you treat functions as expression.
{
Array.prototype.reject = function(fff)
/* Reject is not supported by my engine so i'm implementing it*/
{
let new_array = [];
for (elements of this)
// Loops through every element of an array
{
if (fff(elements) === false)
{
new_array.push(elements);
}
}
return new_array;
}
var animals = [
{"type": "human", "character": "mammal"},
{"type": "dog", "character": "mammal"},
{"type": "fish", "character": "invertebrate"},
]; // This is an animal array which will have object inside it as values
console.log(`Before filter: ${animals}`);
/* Filter section */
var mammals = animals.filter(function(obj){
return obj.character === "mammal";
});
/*
What the heck even is a filter?
Filter is a method in array object,
i) Filter expects you to give a function as a parameter which returns a boolean.
ii) Before executing the function, It creates an empty object
iii) Then it iterates or loops through the array,
calling individual array element to the function and...
iv) Based on the returned boolean upon calling the function with array element
If the function returns true it adds the current element to the empty array.
If the function returns false it rejects to add the current element to the empty array.
v) When the array elements are all iterated over then it returns the newly made array.
*/
console.log(`After filter: ${mammals}`);
/* Reject Section */
var not_mammals = animals.reject(function(obj){
return obj.character === "mammal";
})
console.log(`Not mammals: ${not_mammals}`);
/*
Reject is same as filter, filter pushes the element if the function returns true
but reject pushesh the lement if the function returns false.
*/
}
) // The parenthesis tells JavaScript engine to treat something inside it as expression.
(); // We can call a function expression