本质上,它是一个包含单词的text file,然后围绕它构建了methods.
所以,你只需要获取txt文件的内容,方法几乎是将list转换为字符串数组(而不是将其用作Web服务,这将需要设置模块和API端点处理程序,这里你可以只发送txt文件,并在前端有简单的JS).
您可以简单地复制/粘贴脚本中的列表,或者您可以在服务器/CDN上托管文件(设置一个定期提取新文件的计划作业(job)),然后使用一个简单的脚本来提取文件,并expose 与原始方法相同的方法:
class MyProfanityEngine {
constructor(fileUrl) {
this.fileUrl = fileUrl;
}
// fetch the file from your CDN
async init() {
try {
const res = await fetch(this.fileUrl);
const list = await res.text();
this.terms = list.split('\n');
return true;
} catch (err) {
throw err;
}
}
// use the original methods..
然后在脚本中初始化它:
// pass file url
const profanity = new MyProfanityEngine(fileUrl);
// wait for file fetch and init
await profanity.init();
console.log(await profanity.all()); // returns all bad words as an array.
console.log(await profanity.search('bad word'));
示例:(note that this example uses the original code, and it is just for showcase, you should use your own file CDN)
class MyProfanityEngine {
constructor(fileUrl) {
this.fileUrl = fileUrl;
}
// fetch the file
async init() {
try {
const res = await fetch(this.fileUrl);
const list = await res.text();
this.terms = list.split('\n');
return true;
} catch (err) {
throw err;
}
}
// original methods
async hasCurseWords(sentence) {
if (!this.terms?.length) throw new Error('init first');
const wordsInSentence = sentence.split(/\s+/);
const lowerCasedTerms = this.terms.map((term) => term.toLowerCase());
for (const word of wordsInSentence) {
const lowerCasedWord = word.toLowerCase();
if (lowerCasedTerms.includes(lowerCasedWord)) {
return true;
}
}
return false;
}
async all() {
if (!this.terms?.length) throw new Error('init first');
return this.terms;
}
async search(term) {
if (!this.terms?.length) throw new Error('init first');
return this.terms.includes(term);
}
}
(async() => {
// pass file url, use your own CDN to fetch txt file
const profanity = new MyProfanityEngine('https://raw.githubusercontent.com/coffee-and-fun/google-profanity-words/main/data/en.txt');
// wait for file fetch and init
await profanity.init();
console.log(await profanity.all()); // returns all bad words as an array.
console.log(await profanity.search('bad word')); // returns true if the word is found in the list.
})();