Created
June 7, 2016 20:08
-
-
Save kn9ts/b89133e3d8c76003b3496ca31aa899a8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
// import the file reader | |
const fs = require('fs'); | |
class Index { | |
// method to read the json file | |
readJSONFromFile(filePath) { | |
this.books = JSON.parse(fs.readFileSync(filePath)); | |
} | |
createIndex() { | |
this.indexArray = []; | |
this.books.forEach((book, docIndex) => { | |
var bookObjectString = JSON.stringify(book).toLowerCase().replace(/\W/g, ' ').replace(/\s+/g, ' ').trim(); | |
// console.log('++' + bookObjectString + '++'); | |
this.indexArray = this.indexArray.concat(bookObjectString.split(' ').map((word, wordIndex) => { | |
return (word + ' : ' + docIndex + ' : ' + wordIndex); | |
})); | |
}); | |
} | |
getIndex() { | |
return this.indexArray; | |
} | |
searchIndex(term) { | |
var results = this.indexArray.filter(wordStatistics => { | |
const wordToSearch = new RegExp(term, 'gi'); | |
// if a true boolean is returned, wordStatistics is added to results array | |
return wordToSearch.test(wordStatistics); | |
}); | |
if (results.length === 0) { | |
console.log('No match has been made'); | |
return; | |
} | |
return results; | |
} | |
} | |
// var index = new Index(); | |
// index.readJSONFromFile('book.json'); | |
// index.createIndex(); | |
// console.log(index.getIndex()); | |
// console.log(index.getIndex().length); | |
// console.log(index.searchIndex('and')); | |
exports.module = Index; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment