Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 1)
- function findServer(servers, check) {
- const len = servers.length;
- if (len === 0) {
- return Promise.resolve(null);
- }
- const srvIndex = len / 2;
- const current = servers[srvIndex];
- return check(current).then(checkRes => {
- if (len === 1 && !checkRes) {
- return Promise.resolve(current);
- }
- if (checkRes) {
- // Current server is Ok
- // Look to the right
- return findServer(servers.slice(srvIndex, len), check);
- } else {
- // Current server is not Ok
- // Result is current or to the left of current
- // Must confirm that current is first or find one from the left
- return findServer(servers.slice(0, srvIndex), check).then(leftFindServerResult => {
- if (leftFindServerResult) {
- // findServer() from left is not null => found result earlier in the array
- return Promise.resolve(leftFindServerResult);
- } else {
- // Nothing found to the left of current, returning current
- return Promise.resolve(current);
- }
- })
- }
- });
- }
- // 2)
- const queue = new Map();
- const orderedPrioList = [];
- let runningPrio = null;
- let runningUrls = new Set();
- function addToQueue(cb, prio) {
- const existing = queue.get(prio);
- let arr = [];
- if (existing) {
- arr = existing.value;
- }
- arr.push(cb);
- queue.set(prio, arr);
- }
- function addPrio(prio) {
- if (orderedPrioList.findIndex(prio) !== -1) {
- return;
- }
- orderedPrioList.push(prio);
- orderedPrioList.sort((a, b) => a - b);
- }
- function startNewPrio() {
- if (orderedPrioList.length === 0) {
- return;
- }
- if (runningPrio !== null) {
- queue.delete(runningPrio);
- runningPrio = null;
- }
- const runningPrio = orderedPrioList.pop();
- const qbList = queue.get(runningPrio);
- for(const cb of qbList) {
- cb();
- }
- }
- function load(url, priority) {
- return new Promise((res, reject) => {
- const jobCb = () => {
- runningUrls.add(url);
- try {
- const data = await loadData(url);
- res(data);
- } catch (msg) {
- reject(msg);
- }
- runningUrls.delete(url);
- if (runningUrls.size === 0) {
- startNewPrio();
- }
- };
- // runningPrio === null means queue is empty
- if (!runningPrio || runningPrio === priority) {
- runningPrio = priority;
- runningUrls.add(url);
- jobCb();
- } else {
- addPrio(priority);
- addToQueue(jobCb, priority);
- }
- });
- }
- // 3)
- function camelToSnake(str) {
- return str.replace(/[A-Z]/g, (m) => `_${m.toLowerCase()}`);
- }
Add Comment
Please, Sign In to add comment