-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilter.js
More file actions
77 lines (63 loc) · 2.4 KB
/
filter.js
File metadata and controls
77 lines (63 loc) · 2.4 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
75
76
77
// Concatenate two arrays into a new single array
function concat(array1, array2) {
return array1.concat(array2);
}
// Return the number of items in an array
function length(array) {
return array.length;
}
// Return the first item in an array
function head(array) {
return array[0];
}
// Return the rest of an array after the first item
function tail(array) {
return array.slice(1);
}
wholes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
function filter(predicateFn, array) {
if (length(array) === 0) return [];
const firstItem = head(array);
const filteredFirst = predicateFn(firstItem) ? [firstItem] : [];
return concat(filteredFirst, filter(predicateFn, tail(array)));
}
function isEven(n) {
return n % 2 === 0;
}
evens = filter(isEven, wholes) // [0, 2, 4, 6, 8, 10]
// filetedFirst = isEven(0) ? [firstItem] ; []
// concat(0, filter(predicateFn, [1,2,3,4,5,6,7,8,9,10]))
// concat([], filter(predicateFn, [2,3,4,5,6,7,8,9,10])
// concat(2, filter(predicateFn, [3,4,5,6,7,8,9,10])
// concat([], filter(predicateFn, [4,5,6,7,8,9,10])
// concat(4, filter(predicateFn, [5,6,7,8,9,10])
// concat([], filter(predicateFn, [6,7,8,9,10])
// concat(6, filter(predicateFn, [7,8,9,10])
// concat([], filter(predicateFn, [8,9,10])
// concat(8, filter(predicateFn, [9,10])
// concat([], filter(predicateFn, [10])
// concat(10, filter(predicateFn, [])
// Now we start resolving our chain of functions
// concat(10, filter(predicateFn, []) -> [10]
// concat([], filter(predicateFn, [10]) -> [10]
// concat(8, filter(predicateFn, [10]) -> [8, 10]
// concat([], filter(predicateFn, [8, 10]) -> [8, 10]
// concat(6, filter(predicateFn, [8, 10]) -> [6, 8, 10]
// concat([], filter(predicateFn, [6, 8, 10]) -> [6, 8, 10]
// concat(4, filter(predicateFn, [6, 8, 10]) -> [4, 6, 8, 10]
// concat([], filter(predicateFn, [4, 6, 8, 10]) -> [4, 6, 8, 10]
// concat(2, filter(predicateFn, [4, 6, 8, 10]) -> [2, 4, 6, 8, 10]
// concat([], filter(predicateFn, [2, 4, 6, 8, 10]) -> [2, 4, 6, 8, 10]
// concat(0, filter(predicateFn, [2, 4, 6, 8, 10])) -> [0, 2, 4, 6, 8, 10]
odds = filter(n => {
return !isEven(n);
}, wholes)
[1,3,5,7,9]
greaterThanFour = filter(n => n > 4, wholes)
function isPrime(n) {
if (n <= 1) return false;
const wholes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const possibleFactors = filter(m => m > 1 && m < n, wholes);
const factors = filter(m => n % m === 0, possibleFactors);
return factors.length === 0 ? true : false;
}