-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilter.html
More file actions
83 lines (72 loc) · 2.5 KB
/
filter.html
File metadata and controls
83 lines (72 loc) · 2.5 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
78
79
80
81
82
83
<script src="../simpletest.js"></script>
<script>
// Requirements
// x It should run the call back on each element in the array.
// x It should pass the ith element as the first argument to the callback.
// x It should pass the index as the second argument to the callback.
// x It should pass the array as the third argument in the callback
// x It should accept an optional this object.
// x It should not modify the original array.
// It should return a new array.
// The new array should only contain elements when the callback returns true.
function filter(originalArray, callback, optionalThisArgument) {
var filteredArray = [];
var filterCallback = callback;
if (optionalThisArgument) {
filterCallback = callback.bind(optionalThisArgument);
}
for(var i = 0; i < originalArray.length; i++){
if(filterCallback(originalArray[i], i, originalArray)) {
filteredArray.push(originalArray[i]);
}
}
return filteredArray;
}
tests({
'It should run the callback function array.length times': function() {
var runCount = 0;
filter([1,2,3],function(){
runCount++;
})
eq(runCount,3);
},
'It should pass in the ith element as the first argument to the callback': function() {
filter([3],function(number){
eq(3, number);
})
},
'It should pass in the ith position as the second arguement to the callback': function() {
filter([1],function(number, index){
eq(0,index);
})
},
'It should pass in the original array as the third argument to the callback': function() {
var testArray = [1,2,3];
filter(testArray, function (number, index, originalArray){
eq(originalArray,testArray);
})
},
'It should accept an optional this object': function () {
filter([1], function() {
eq(this.description,"I should be accessible within the callback");
}, {description:"I should be accessible within the callback"})
},
'It should not modify the original array': function () {
var testArray = [1,2,3];
var testCopy = [1,2,3];
filter(testArray,function (number,index, array){
eq(array[index],testCopy[index]);
});
},
'It should return a new array': function () {
Array.isArray(filter([1,2,3], function(){}));
},
'It should return elements where the callback is true': function() {
var filteredArray = filter([1,2],function (number){
return number > 1;
});
eq(1,filteredArray.length);
eq(2,filteredArray[0]);
}
});
</script>