Skip to content

Commit aa8b12a

Browse files
committed
added tests
1 parent c439238 commit aa8b12a

File tree

3 files changed

+32
-10
lines changed

3 files changed

+32
-10
lines changed

package.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"description": "Mind under construction",
55
"main": "index.js",
66
"scripts": {
7-
"test": "echo \"Error: no test specified\" && exit 1"
7+
"test": "tap -J test/**/*.test.js"
88
},
99
"repository": {
1010
"type": "git",
@@ -21,6 +21,7 @@
2121
},
2222
"homepage": "https://github.com/Eomm/grokking#readme",
2323
"devDependencies": {
24-
"standard": "^12.0.1"
24+
"standard": "^12.0.1",
25+
"tap": "^12.6.1"
2526
}
2627
}

search/binary-search.js

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,29 +5,28 @@
55
* Constraint: Array must be sorted
66
*/
77

8-
Array.prototype.binarySearch = function binarySearch(searchFor) {
8+
Array.prototype.binarySearch = function binarySearch (searchFor) { // eslint-disable-line no-extend-native
99
let low = 0
1010
let high = this.length - 1
1111

1212
let steps = 0
1313
while (low <= high) {
1414
steps++
15-
console.log(`Step ${steps}`);
15+
// console.log(`Step ${steps}`)
1616

1717
const middle = Math.round((low + high) / 2)
1818
const guess = this[middle]
1919
if (guess === searchFor) {
20-
return middle
20+
return { found: middle, steps }
2121
} else if (guess > searchFor) {
2222
high = middle - 1
2323
} else {
2424
low = middle + 1
2525
}
2626
}
27-
return null
27+
return { found: null, steps }
2828
}
2929

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+
}

test/search/binary-search.test.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
})

0 commit comments

Comments
 (0)