Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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