Parallel

Asynchronous array handle

بۇ قوليازمىنى بىۋاسىتە قاچىلاشقا بولمايدۇ. بۇ باشقا قوليازمىلارنىڭ ئىشلىتىشى ئۈچۈن تەمىنلەنگەن ئامبار بولۇپ، ئىشلىتىش ئۈچۈن مېتا كۆرسەتمىسىگە قىستۇرىدىغان كود: // @require https://update.greatest.deepsurf.us/scripts/380535/680853/Parallel.js

  1. // ==UserScript==
  2. // @name Parallel
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.2
  5. // @description Asynchronous array handle
  6. // @author You
  7. // ==/UserScript==
  8.  
  9. class Parallel{
  10. constructor(count=3){
  11. this.count=3
  12. }
  13.  
  14. partial(data,count){
  15. let r=[];
  16. let l=data.length;
  17. let dataPerThread=parseInt(l/count);
  18. if (dataPerThread==0){
  19. dataPerThread=1;
  20. }
  21. for (let i=0;i<l;i+=dataPerThread){
  22. let to=Math.min(i+dataPerThread,l);
  23. let d=data.slice(i,to);
  24. r.push(d);
  25. }
  26. return r;
  27. }
  28.  
  29. async run(data,action,isReturn=false){
  30. let results=[];
  31. for (let x in data){
  32. let r=action(data[x]);
  33. if (r instanceof Promise){
  34. r=await r;
  35. }
  36. if (isReturn){
  37. results.push(r);
  38. }
  39. }
  40. if (isReturn){
  41. return results;
  42. }
  43. }
  44.  
  45. async forEach(data,action){
  46. data=this.partial(data,this.count);
  47. let threads=[];
  48. for (let i in data){
  49. let d=data[i];
  50. threads.unshift(this.run(d,action));
  51. }
  52. for (let x in threads){
  53. await threads[x];
  54. }
  55. }
  56.  
  57. async map(data,action){
  58. data=this.partial(data,this.count);
  59. let threads=[];
  60. for (let i in data){
  61. let d=data[i];
  62. threads.unshift(this.run(d,action,true));
  63. }
  64. let results=[];
  65. for (let x in threads){
  66. results=results.concat(await threads[x]);
  67. }
  68. return results;
  69. }
  70. }