Electron-Svelte-Recipe-Planner/package/public/worker.js
2021-12-16 00:55:59 -05:00

92 lines
3 KiB
JavaScript

var buffer = "sdrf;glk"
importScripts("fastdice.js")
var jsonlookup
var bufferdate = 0
async function queryServer(search, big = true) {
console.log(jsonlookup)
var final = []
return new Promise(resolve => {
var key = []
for (let i in jsonlookup) {
var coefficent = dice(search, jsonlookup[i]["name"])
var img = jsonlookup[i]["imgurl"]
if (img.length < 13){
//this sets the default image if there is not likely to be one
img = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT-zqUA_lTBN0HNgeNisDcJdfPRhaLHnww1dQ&usqp=CAU"
}
//this makes key a tuple of this stuff
key.push(
[coefficent, jsonlookup[i]["name"], jsonlookup[i]["author"],
jsonlookup[i]["url"], jsonlookup[i]["dateadded"], img]
)
}
key.sort(function (a, b) { return b[0] - a[0]; })
//makes it so small searches do less operations.
if (big == true){
//the != sets the total amount of entries.
//added from key
for (let i = 0; final.length != 40; i++) {
var id = {"name" : key[i][1],
"author" : key[i][2], "url" : key[i][3],
"dateadded" : key[i][4], "imgurl" : key[i][5]}
//sorts out duplicats theroetically, however it doesn't always work in practice.
//must add a more complex check here :)
if (!final.includes(id)) {
final.push(id)
}
}
bufferdate = Date.now()
resolve(JSON.stringify(final))
}
else{ resolve(key[0]) }
})
}
//is a smaller search
async function autoupdate(value){
if (value != buffer) {
if (value.length > 2) {
ping = []
var sdo = await queryServer(value, false)
//denotes this as a small baby
self.postMessage(sdo+="≈")
console.log("sent")
buffer = value
}
}
}
function searchSelectedRecipes(a,b)
var recieved = 0 //for some reason i cant edit the var before its in the scope.
self.onmessage = function (value) {
var value = value["data"]
if (recieved == 0){
console.log(value)
jsonlookup = JSON.parse(value)
recieved = 1
console.log("json recieved")
}
//this checks if its a smaller request(denoted by the squigly equals)
//creates buffer so it doesn't overflow and crash
else if (value.includes("≈") && (Date.now()/1000) - (bufferdate/1000) > 0.5){
autoupdate(value.slice(0, -1))
} //I got that character from random utf-8, i've never seen, it even in dwarf fortress
else if (value.contains("گ")){
}
else{
var y = queryServer(value).then(returned => {
self.postMessage(String(returned))})
}
}