사용자:BANIP/script/랭킹시스템
function RankingSystem(documentTitle, sortCallback, api) {
function forEach(object, callback) { for (var key in object) { var variable = object[key]; callback(variable, key); } }
function getRankingJSON(rankingDoc) { if (!rankingDoc) return {}; var includeOnlyString = "includeonly" var regexp = new RegExp("\<" + includeOnlyString + "\>(.*)\<\/" + includeOnlyString + "\>"); var stringRanking = regexp.exec(rankingDoc)[1]; return JSON.parse(stringRanking); }
function updateDoc(rankingJSON, api, alternateKeys) { //alternateKeys가 반영된 개개인의 랭킹정보 획득 function getOutputJSON(json) { var result = {}; forEach(json, function(value, key) { key = alternateKeys[key] || key; result[key] = value; }) return result; }
//보여지는 형태의 랭킹정보 획득 function getOutputString(json) { var name = json.name; var result = "* " + name + " : "; forEach(json, function(value, key) { if (key === "name") return; key = alternateKeys[key] || key; result += key + ": " + value + ", "; }) result += "\n" return result }
var stringRanking = JSON.stringify(rankingJSON); var result = "<includ" + "eonly>" + stringRanking + "</inclu" + "deonly>\n"; result += "<onlyin" + "clude>\n";
var rankingList = Object.entries(rankingJSON).sort(function(prev,next){ return sortCallback(prev[1],next[1]) }).map(function(value){ return value[0] });
rankingList.forEach(function(key) { var json = rankingJSON[key]; var outputJSON = getOutputJSON(json); result += getOutputString(outputJSON) });
result += "</only" + "include>"; var reply = documentTitle.replace(new RegExp("\/.*"),"") + " 점수 갱신"; api.changeDocument(documentTitle, reply, result, true); return result; }
function updateUserScore(rankingJSON, thisScore, updateCriteria) { updateCriteria = updateCriteria || function(rankingScore, thisScore) { return rankingScore.score < thisScore.score; }
var userName = thisScore.name; var rankingScore = rankingJSON[userName];
if (!rankingScore || updateCriteria(rankingScore, thisScore)) { rankingJSON[userName] = thisScore; } }
api = api || MediaWikiAPI(); var userName = mw.config.get("wgUserName"); var rankingDoc = api.getDocument(documentTitle); var rankingJSON = getRankingJSON(rankingDoc);
var actions = { get: function() { return rankingJSON; }, update: function(updateInfo, updateCriteria, alternateKeys) { rankingJSON = actions.get(); updateUserScore(rankingJSON, updateInfo, updateCriteria); updateDoc(rankingJSON, api, alternateKeys); } } return actions;
}