Skip to content

Instantly share code, notes, and snippets.

@kn9ts
Created June 7, 2016 20:08
Show Gist options
  • Save kn9ts/b89133e3d8c76003b3496ca31aa899a8 to your computer and use it in GitHub Desktop.
Save kn9ts/b89133e3d8c76003b3496ca31aa899a8 to your computer and use it in GitHub Desktop.
'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