search.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. var fs = require('fs');
  2. var Fuse = require('fuse.js');
  3. var client = new (require('github'))({
  4. version: '3.0.0'
  5. });
  6. require('colors');
  7. var notEmpty = function(str) { return !!str.trim(); };
  8. var trim = function(str) { return str.trim(); };
  9. var fetch = function(callback) {
  10. // TODO cache
  11. client.repos.getContent({
  12. user: 'JuanitoFatas',
  13. repo: 'Computer-Science-Glossary',
  14. path: 'dict.textile',
  15. ref: 'master'
  16. }, function(err, res) {
  17. callback(err, new Buffer(res.content, 'base64').toString('utf8'));
  18. });
  19. };
  20. var search = function(content, key) {
  21. var reg = /h2\. ([A-Z])([^]*?)(?=h2\. [A-Z])/g;
  22. var match,
  23. table = [];
  24. while (match = reg.exec(content)) {
  25. match[2].split('\n')
  26. .filter(notEmpty)
  27. .slice(1)
  28. .forEach(function(entry) {
  29. var words = entry.split('|').filter(notEmpty).map(trim);
  30. table.push({origin: words[0], translations: words.slice(1)});
  31. });
  32. }
  33. var fuse = new Fuse(table, {keys: ['origin']});
  34. return fuse.search(key).slice(0, 3);
  35. };
  36. module.exports = function(key) {
  37. fetch(function(err, content) {
  38. if (err) throw err;
  39. var results = search(content, key);
  40. console.log('Fuzzy match including: '.grey);
  41. results.forEach(function(entry) {
  42. console.log(entry.origin.green);
  43. entry.translations.forEach(function(translation) {
  44. console.log(' ' + translation.blue);
  45. });
  46. });
  47. });
  48. };