Parcourir la source

Création class finder

Loquicom il y a 5 ans
Parent
commit
06b68cb6ad
2 fichiers modifiés avec 82 ajouts et 0 suppressions
  1. 73 0
      src/finder/finder.js
  2. 9 0
      src/finder/index.js

+ 73 - 0
src/finder/finder.js

@@ -0,0 +1,73 @@
+const readline = require('readline');
+const file = require('../file');
+
+let instance = null;
+
+const finder = class Finder {
+
+    constructor() {
+        this.result = [];
+        this.name = '';
+        this.source = null;
+        this.callback = null;
+        this.reader = null;
+    }
+
+    from(source) {
+        if (!file.exist(source)) {
+            throw 'Unable to find the source file';
+        }
+        this.source = source;
+        return this;
+    }
+
+    find(name, callback = null) {
+        if (this.source === null) {
+            throw 'No source file';
+        }
+        this.callback = callback;
+        this.name = name;
+        this.reader = readline.createInterface({
+            input: file.fs.createReadStream(this.source)
+        });
+        this.reader.on('line', this._line);
+        this.reader.on('close', this._close);
+    }
+
+    _line(content) {
+        const group = JSON.parse(content);
+        if (group.indexOf(instance.name) !== -1) {
+            instance.result.push(group);
+        }
+    }
+
+    _close() {
+        // Retire les doublons et l'auteur choisit
+        let coauth = [];
+        instance.result.forEach(group => {
+            group.forEach(elt => {
+                if (elt !== instance.name && coauth.indexOf(elt) === -1) {
+                    coauth.push(elt);
+                }
+            });
+        });
+        // Tri par ordre alphabetique
+        coauth.sort(instance._alphabeticalSort);
+        // Retour
+        if (instance.callback !== null) {
+            instance.callback(coauth);
+        }
+    }
+
+    _alphabeticalSort(a, b) {
+        return (a > b) ? 1 : -1;
+    }
+
+};
+
+module.exports.get = function () {
+    if (instance === null) {
+        instance = new finder();
+    }
+    return instance;
+};

+ 9 - 0
src/finder/index.js

@@ -0,0 +1,9 @@
+const finder = require('./finder').get();
+
+module.exports.in = function (path) {
+    return finder.from(path);
+};
+
+module.exports.get = function () {
+    return finder;
+};