source: imaps-frontend/node_modules/p-locate/index.js

main
Last change on this file was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 1.1 KB
Line 
1'use strict';
2const pLimit = require('p-limit');
3
4class EndError extends Error {
5 constructor(value) {
6 super();
7 this.value = value;
8 }
9}
10
11// The input can also be a promise, so we await it
12const testElement = async (element, tester) => tester(await element);
13
14// The input can also be a promise, so we `Promise.all()` them both
15const finder = async element => {
16 const values = await Promise.all(element);
17 if (values[1] === true) {
18 throw new EndError(values[0]);
19 }
20
21 return false;
22};
23
24const pLocate = async (iterable, tester, options) => {
25 options = {
26 concurrency: Infinity,
27 preserveOrder: true,
28 ...options
29 };
30
31 const limit = pLimit(options.concurrency);
32
33 // Start all the promises concurrently with optional limit
34 const items = [...iterable].map(element => [element, limit(testElement, element, tester)]);
35
36 // Check the promises either serially or concurrently
37 const checkLimit = pLimit(options.preserveOrder ? 1 : Infinity);
38
39 try {
40 await Promise.all(items.map(element => checkLimit(finder, element)));
41 } catch (error) {
42 if (error instanceof EndError) {
43 return error.value;
44 }
45
46 throw error;
47 }
48};
49
50module.exports = pLocate;
Note: See TracBrowser for help on using the repository browser.