Skip to content

Commit 7c8d0e2

Browse files
committed
fix(*): support for better filtering
adds support for whitelisting. refactored isProfane to do regex comparisons. added new method isProfaneLike to test a single word against the whitelist, 1-1 comparison to blacklist, and regex test against blacklist #20
1 parent 9d05d5a commit 7c8d0e2

File tree

1 file changed

+31
-15
lines changed

1 file changed

+31
-15
lines changed

lib/badwords.js

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,36 @@ var Filter = (function() {
22
function Filter(options) {
33
options = options || {};
44
this.list = options.emptyList && [] || Array.prototype.concat.apply(require('./lang.json').words, [require('badwords-list').array, options.list || []]);
5+
this.exclude = options.exclude || [];
56
this.placeHolder = options.placeHolder || '*';
67
this.regex = options.regex || /[^a-zA-z0-9|\$|\@]|\^/g;
78
this.replaceRegex = options.replaceRegex || /\w/g;
89
}
910

1011
Filter.prototype.isProfane = function isProfane(string) {
11-
var words = string.split(' ');
12-
for (var j = 0; j < words.length; j++) {
13-
var word = words[j].toLowerCase().replace(this.regex, '');
14-
if (~this.list.indexOf(word)) {
15-
return true;
16-
}
17-
}
18-
return false;
12+
return string
13+
.split(' ')
14+
.map(function(w) {
15+
return w.toLowerCase().replace(this.regex, '');
16+
}, this)
17+
.map(this.isProfaneLike, this)
18+
.filter(function(profane) {
19+
return profane;
20+
})
21+
.shift() || false;
22+
};
23+
24+
Filter.prototype.isProfaneLike = function profaneLike(word) {
25+
return !!~this.exclude.indexOf(word) ? false : !!~this.list.indexOf(word) || this.list
26+
.map(function(w) {
27+
return new RegExp(w.replace(/(\W)/g, '\\$1'));
28+
}, this)
29+
.reduce(function(outcome, wordExp) {
30+
if (wordExp.test(word)) {
31+
return true;
32+
}
33+
return outcome;
34+
}, false);
1935
};
2036

2137
Filter.prototype.replaceWord = function replaceWord(string) {
@@ -31,17 +47,17 @@ var Filter = (function() {
3147
Filter.prototype.addWords = function addWords(words) {
3248
words = (words instanceof Array) ? words : [words];
3349
this.list = this.list.concat(words);
50+
51+
words.forEach(function(word) {
52+
if(!!~this.exclude.indexOf(word)) {
53+
this.exclude.splice(this.exclude.indexOf(word), 1);
54+
}
55+
}, this);
3456
};
3557

3658
Filter.prototype.removeWords = function removeWords() {
3759
var words = Array.prototype.slice.call(arguments);
38-
words.map(function(word) {
39-
return this.list.indexOf(word);
40-
}, this).filter(function(index) {
41-
return !!~index;
42-
}).forEach(function(index){
43-
this.list.splice(index, 1);
44-
}, this);
60+
this.exclude.push.apply(this.exclude, words);
4561
};
4662

4763
return Filter;

0 commit comments

Comments
 (0)