smartfuzzy/ts/smartfuzzy.articlesearch.ts
2021-10-03 17:24:17 +02:00

66 lines
1.7 KiB
TypeScript

import * as plugins from './smartfuzzy.plugins';
/**
* an article search that searches articles in a weighted manner
*/
export class ArticleSearch {
public articles: plugins.tsclass.content.IArticle[] = [];
public needsUpdate: boolean = false;
private readyDeferred = plugins.smartpromise.defer();
private fuse: plugins.fuseJs<plugins.tsclass.content.IArticle>;
constructor(articleArrayArg?: plugins.tsclass.content.IArticle[]) {
this.fuse = new plugins.fuseJs(this.articles);
this.readyDeferred.resolve();
if (articleArrayArg) {
for (const article of articleArrayArg) {
this.addArticle(article);
}
}
}
/**
* allows adding an article
*/
addArticle(articleArg: plugins.tsclass.content.IArticle) {
this.articles.push(articleArg);
this.needsUpdate = true;
}
/**
* allows searching an article
*/
public async search(searchStringArg: string) {
if (this.needsUpdate) {
const oldDeferred = this.readyDeferred;
this.readyDeferred = plugins.smartpromise.defer();
this.needsUpdate = false;
if (oldDeferred.status !== 'fulfilled') {
this.readyDeferred.promise.then(oldDeferred.resolve);
}
this.fuse = new plugins.fuseJs(this.articles, {
keys: [
{
name: 'title',
weight: 3,
},
{
name: 'tags',
weight: 2,
},
{
name: 'content',
weight: 1,
},
],
includeMatches: true
});
this.readyDeferred.resolve();
} else {
await this.readyDeferred.promise;
}
return this.fuse.search(searchStringArg);
}
}