Skip to content

Instantly share code, notes, and snippets.

@erayarslan
Created January 9, 2017 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erayarslan/8262513020d54071d23a3f43f238d35c to your computer and use it in GitHub Desktop.
Save erayarslan/8262513020d54071d23a3f43f238d35c to your computer and use it in GitHub Desktop.
flack.js
(function () {
var root = this;
var flack = function (limit, blackList) {
this.blackList = typeof blackList === "undefined" ? [] : blackList;
this.limit = typeof limit === "undefined" ? 50 : parseInt(limit);
this.obj = {};
};
if (typeof exports !== "undefined") {
if (typeof module !== "undefined" && module.exports) {
exports = module.exports = flack;
}
exports.flack = flack;
} else {
root.flack = flack;
}
flack.prototype.push = function (reportedMessage) {
reportedMessage = reportedMessage.toLowerCase();
var arr = reportedMessage.match(/\S+/g);
arr = arr.filter(function(item, position) {
return arr.indexOf(item) == position;
});
for (var i in arr) {
if (this.blackList.indexOf(arr[i]) != -1) {
continue;
}
if (this.obj.hasOwnProperty(arr[i])) {
this.obj[arr[i]]++;
} else {
this.obj[arr[i]] = 1;
}
}
};
flack.prototype.pop = function () {
var found = false;
var biggestKey;
var firstFound = false;
for (var key in this.obj) {
if (this.obj[key] >= this.limit) {
found = true;
if (!firstFound) {
biggestKey = key;
firstFound = true;
} else {
if (this.obj[key] > this.obj[biggestKey]) {
biggestKey = key;
}
}
}
}
if (found) {
delete this.obj[biggestKey];
return biggestKey;
}
};
flack.prototype.start = function (callback, interval) {
if (typeof callback !== "function") {
throw new Error("callback not a function.");
}
var self = this;
this.timer = setInterval(function () {
callback(self.pop());
}, interval || 30000);
};
flack.prototype.stop = function () {
clearInterval(this.timer);
};
if (typeof define === 'function' && define.amd) {
define('flack', [], function () {
return flack;
});
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment