finder.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const readline = require('readline');
  2. const file = require('../../file');
  3. const result = require('./result');
  4. let instance = null;
  5. const finder = class Finder {
  6. constructor() {
  7. this.result = [];
  8. this.name = '';
  9. this.source = null;
  10. this.callback = null;
  11. this.reader = null;
  12. }
  13. from(source) {
  14. if (!file.exist(source)) {
  15. throw 'Unable to find the source file';
  16. }
  17. this.source = source;
  18. return this;
  19. }
  20. find(name, callback = null) {
  21. if (this.source === null) {
  22. throw 'No source file';
  23. }
  24. this.callback = callback;
  25. this.name = name;
  26. this.reader = readline.createInterface({
  27. input: file.fs.createReadStream(this.source)
  28. });
  29. this.reader.on('line', this._line);
  30. this.reader.on('close', this._close);
  31. }
  32. _line(content) {
  33. const group = JSON.parse(content);
  34. if (group.indexOf(instance.name) !== -1) {
  35. instance.result.push(group);
  36. }
  37. }
  38. _close() {
  39. // Retire les doublons et l'auteur choisit
  40. let coauth = [];
  41. instance.result.forEach(group => {
  42. group.forEach(elt => {
  43. if (elt !== instance.name && coauth.indexOf(elt) === -1) {
  44. coauth.push(elt);
  45. }
  46. });
  47. });
  48. // Retour
  49. let res = new result();
  50. res.name = instance.name;
  51. res.coAuthors = coauth;
  52. if (instance.callback !== null) {
  53. instance.callback(res);
  54. }
  55. }
  56. };
  57. module.exports.get = function () {
  58. if (instance === null) {
  59. instance = new finder();
  60. }
  61. return instance;
  62. };