-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind.html
More file actions
87 lines (73 loc) · 2.32 KB
/
find.html
File metadata and controls
87 lines (73 loc) · 2.32 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
84
85
86
87
<script src="../simpletest.js"></script>
<script>
// Prototype Function
// function find(originalArray, callback) {
// for(var i = 0; i < originalArray.length; i++) {
// if(callback(originalArray[i], i, originalArray)) {
// return array[i];
// }
// }
// }
function myFind(originalArray,callback, optionalThisArgument) {
var findCallback = callback;
var maxRunCount = originalArray.length;
if(arguments.length >= 3) {
findCallback = callback.bind(optionalThisArgument);
}
for(var i = 0; i < maxRunCount; i++) {
if(findCallback(originalArray[i], i, originalArray)) {
return originalArray[i];
}
}
};
tests({
'It should return the first element in the array that the callback returns true.': function() {
var result = myFind([1,2,3],function(number){
return number > 2;
})
eq(result,3);
},
'It should return undefined if no element in array returns true by callback': function() {
var result = myFind([1,2,3],function(number){
return number > 3;
})
eq(result,undefined);
},
'It should pass in the ith element as the first argument to the callback': function() {
myFind([3],function(number){
eq(3, number);
})
},
'It should pass in the index as the second arguement to the callback': function() {
myFind([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];
myFind(testArray, function (number, index, originalArray){
eq(originalArray,testArray);
})
},
'It should accept an optional this object': function () {
myFind([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];
myFind(testArray,function (number,index, array){
eq(array[index],testCopy[index]);
});
},
'It should run <= originalArray.length times.': function () {
var runCount = 0;
myFind([1,2,3],function(number, index, array){
runCount++;
array.push('66');
})
eq(runCount,3);
}
});
</script>