SHARE
TWEET

Untitled

a guest Apr 18th, 2019 75 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // 21:13
  2. // Given urls ['url1', 'url2', 'url2', 'url3'...], limit
  3. // Function `process` should `get` all urls, respecting limit and return when finished.
  4. // Limit means that at the same time there should be N (limit) requests in progress, at least and at most
  5. // Duplicate urls shouldn't be processed again, but the final order should be the same
  6. // Get is used to mock requests
  7. function get(url) {
  8.   return Promise.resolve("result" + url);
  9. }
  10.  
  11. // Checkpoint 21:22
  12. // Checkpoint 21:34
  13.  
  14. function process(urls, limit) {
  15.   async function _process() {
  16.     const urlMap = {};
  17.     const first10urls = urls.slice(0, limit);
  18.     const restUrls = urls.slice(limit);
  19.     const res = [];
  20.  
  21.     function processNext(url, resolve) {
  22.       if (!urlMap[url]) {
  23.         urlMap[url] = get(url).then(res => {
  24.           if (restUrls.length) {
  25.             nextUrl = restUrls.pop();
  26.             processNext(nextUrl, resolve);
  27.           } else {
  28.             resolve();
  29.           }
  30.           return res;
  31.         });
  32.       }
  33.     }
  34.  
  35.     function wait() {
  36.       return new Promise(resolve => {
  37.         first10urls.forEach(url => {
  38.           processNext(url, resolve);
  39.         });
  40.       });
  41.     }
  42.  
  43.     await wait();
  44.     // urlMap should be full by that time
  45.  
  46.     for (let url of urls) {
  47.       const data = await urlMap[url];
  48.       res.push(data);
  49.     }
  50.  
  51.     return res;
  52.   }
  53.  
  54.   return _process();
  55. }
  56.  
  57. // 21:39
  58. // Handle wait for all promies
  59. // Done 21:45
  60.  
  61. console.log(
  62.   process(["url1", "url2", "url3", "url4", "url5", "url6", "url7", "url2"], 2)
  63. );
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top