File tree Expand file tree Collapse file tree 3 files changed +32
-10
lines changed Expand file tree Collapse file tree 3 files changed +32
-10
lines changed Original file line number Diff line number Diff line change 4
4
"description" : " Mind under construction" ,
5
5
"main" : " index.js" ,
6
6
"scripts" : {
7
- "test" : " echo \" Error: no test specified \" && exit 1 "
7
+ "test" : " tap -J test/**/*.test.js "
8
8
},
9
9
"repository" : {
10
10
"type" : " git" ,
21
21
},
22
22
"homepage" : " https://github.com/Eomm/grokking#readme" ,
23
23
"devDependencies" : {
24
- "standard" : " ^12.0.1"
24
+ "standard" : " ^12.0.1" ,
25
+ "tap" : " ^12.6.1"
25
26
}
26
27
}
Original file line number Diff line number Diff line change 5
5
* Constraint: Array must be sorted
6
6
*/
7
7
8
- Array . prototype . binarySearch = function binarySearch ( searchFor ) {
8
+ Array . prototype . binarySearch = function binarySearch ( searchFor ) { // eslint-disable-line no-extend-native
9
9
let low = 0
10
10
let high = this . length - 1
11
11
12
12
let steps = 0
13
13
while ( low <= high ) {
14
14
steps ++
15
- console . log ( `Step ${ steps } ` ) ;
15
+ // console.log(`Step ${steps}`)
16
16
17
17
const middle = Math . round ( ( low + high ) / 2 )
18
18
const guess = this [ middle ]
19
19
if ( guess === searchFor ) {
20
- return middle
20
+ return { found : middle , steps }
21
21
} else if ( guess > searchFor ) {
22
22
high = middle - 1
23
23
} else {
24
24
low = middle + 1
25
25
}
26
26
}
27
- return null
27
+ return { found : null , steps }
28
28
}
29
29
30
- const sortedArray = Array ( 1024 ) . fill ( 0 ) . map ( ( _ , i ) => i )
31
-
32
- const output = sortedArray . binarySearch ( 800 )
33
- console . log ( `Result ${ output } ` ) ;
30
+ module . exports = function ( searchFor , inArray ) {
31
+ return inArray . binarySearch ( searchFor )
32
+ }
Original file line number Diff line number Diff line change
1
+ 'use strict'
2
+
3
+ const { test } = require ( 'tap' )
4
+ const binarySearch = require ( '../../search/binary-search' )
5
+
6
+ test ( 'binary search' , t => {
7
+ t . plan ( 2 )
8
+
9
+ t . test ( 'found' , t => {
10
+ t . plan ( 1 )
11
+ const sortedArray = Array ( 1024 ) . fill ( 0 ) . map ( ( _ , i ) => i )
12
+ const res = binarySearch ( 800 , sortedArray )
13
+ t . deepEquals ( res , { found : 800 , steps : 5 } )
14
+ } )
15
+
16
+ t . test ( 'not found' , t => {
17
+ t . plan ( 1 )
18
+ const sortedArray = Array ( 1024 ) . fill ( 0 ) . map ( ( _ , i ) => i )
19
+ const res = binarySearch ( 2000 , sortedArray )
20
+ t . deepEquals ( res , { found : null , steps : 10 } )
21
+ } )
22
+ } )
You can’t perform that action at this time.
0 commit comments