-
Notifications
You must be signed in to change notification settings - Fork 1
/
binarysearcher.js
75 lines (51 loc) · 1.68 KB
/
binarysearcher.js
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
'use strict';
const argv = require('yargs').argv;
const _ = require('lodash');
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
const readline = require('readline');
const chop = require('./chop.js');
class BinarySearcher {
constructor(numberlist) {
this.numberlist = numberlist;
}
load(numberlist) {
numberlist = numberlist || this.numberlist;
return fs
.readFileAsync(numberlist)
.then((numberlistBuffer) => {
let numberlistArray = numberlistBuffer.toString().split('\n');
this.haystack = numberlistArray.map((num) => parseInt(num));
});
}
search(needle) {
return chop(needle, this.haystack);
}
static main() {
let numberlist = argv.numberlist || 'numberlist.txt';
let bsch = new BinarySearcher(numberlist);
const rl = Promise.promisifyAll(readline.createInterface({
input: process.stdin,
output: process.stdout
}));
bsch.load()
.then(() => {
promptForSearch();
function promptForSearch(dictionary) {
rl.question('Enter a number [CTRL+C to exit]: ', (search) => {
let idx = bsch.search(parseInt(search));
if (idx === -1) {
console.log(`${search} is not in the list`);
} else {
console.log(`${search} is at line ${idx + 1}`);
}
return promptForSearch();
});
}
});
}
}
module.exports = BinarySearcher;
if (require.main === module) {
BinarySearcher.main();
}