port algorithm for normalizing known instances to five visible slots

This commit is contained in:
codl 2019-03-15 20:25:45 +01:00
parent 17f59a018f
commit 915a6029d7
No known key found for this signature in database
GPG Key ID: 6CD7C8891ED1233A
1 changed files with 59 additions and 3 deletions

View File

@ -1,5 +1,7 @@
(function instance_buttons(){ (function instance_buttons(){
const SLOTS = 5;
const STORAGE_KEY = 'forget_known_instances'; const STORAGE_KEY = 'forget_known_instances';
const container = document.querySelector('#mastodon_instance_buttons'); const container = document.querySelector('#mastodon_instance_buttons');
@ -20,19 +22,73 @@
known = await resp.json(); known = await resp.json();
} }
else { else {
known = []; known = [{
"instance": "mastodon.social",
"hits": 0
}];
} }
localStorage.setItem(STORAGE_KEY, JSON.stringify(known)); save(known)
fetch('/api/known_instances', {method: 'DELETE'}) fetch('/api/known_instances', {method: 'DELETE'})
} }
return known; return known;
} }
function normalize(known){
/*
move instances with the most hits to the top SLOTS slots,
making sure not to reorder anything that is already there
*/
let head = known.slice(0, SLOTS);
let tail = known.slice(SLOTS);
if(tail.length == 0){
return known;
}
for(let i = 0; i < SLOTS; i++){
let head_min = head.reduce((acc, cur) => acc.hits < cur.hits ? acc : cur);
let tail_max = tail.reduce((acc, cur) => acc.hits > cur.hits ? acc : cur);
if(head_min.hits < tail_max.hits){
// swappy
let i = head.indexOf(head_min);
let j = tail.indexOf(tail_max);
let buf = head[i];
head[i] = tail[j];
tail[j] = buf;
}
}
return head.concat(tail)
}
function save(known){
localStorage.setItem(STORAGE_KEY, JSON.stringify(known));
}
async function replace_buttons(){ async function replace_buttons(){
let known = await get_known(); let known = await get_known();
let instances = known.concat(top_instances).slice(0, 5); known = normalize(known);
save(known);
let filtered_top_instances = []
for(let instance of top_instances){
let found = false;
for(let k of known){
if(k['instance'] == instance){
found = true;
break;
}
}
if(!found){
filtered_top_instances.push(instance)
}
}
let instances = known.concat(filtered_top_instances).slice(0, SLOTS);
let html = ''; let html = '';