@common.js/p-locate 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # @common.js/p-locate
2
+
3
+ The [p-locate](https://www.npmjs.com/package/p-locate) package exported as CommonJS modules.
4
+
5
+ Exported from [p-locate@6.0.0](https://www.npmjs.com/package/p-locate/v/6.0.0) using https://github.com/etienne-martin/common.js.
package/index.d.ts ADDED
@@ -0,0 +1,49 @@
1
+ export interface Options {
2
+ /**
3
+ The number of concurrently pending promises returned by `tester`.
4
+
5
+ Minimum: `1`
6
+
7
+ @default Infinity
8
+ */
9
+ readonly concurrency?: number;
10
+
11
+ /**
12
+ Preserve `input` order when searching.
13
+
14
+ Disable this to improve performance if you don't care about the order.
15
+
16
+ @default true
17
+ */
18
+ readonly preserveOrder?: boolean;
19
+ }
20
+
21
+ /**
22
+ Get the first fulfilled promise that satisfies the provided testing function.
23
+
24
+ @param input - An iterable of promises/values to test.
25
+ @param tester - This function will receive resolved values from `input` and is expected to return a `Promise<boolean>` or `boolean`.
26
+ @returns A `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`.
27
+
28
+ @example
29
+ ```
30
+ import {pathExists} from 'path-exists';
31
+ import pLocate from 'p-locate';
32
+
33
+ const files = [
34
+ 'unicorn.png',
35
+ 'rainbow.png', // Only this one actually exists on disk
36
+ 'pony.png'
37
+ ];
38
+
39
+ const foundPath = await pLocate(files, file => pathExists(file));
40
+
41
+ console.log(foundPath);
42
+ //=> 'rainbow'
43
+ ```
44
+ */
45
+ export default function pLocate<ValueType>(
46
+ input: Iterable<PromiseLike<ValueType> | ValueType>,
47
+ tester: (element: ValueType) => PromiseLike<boolean> | boolean,
48
+ options?: Options
49
+ ): Promise<ValueType | undefined>;
package/index.js ADDED
@@ -0,0 +1,421 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "default", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return pLocate;
9
+ }
10
+ });
11
+ var _pLimit = /*#__PURE__*/ _interopRequireDefault(require("p-limit"));
12
+ function _arrayLikeToArray(arr, len) {
13
+ if (len == null || len > arr.length) len = arr.length;
14
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
15
+ return arr2;
16
+ }
17
+ function _arrayWithoutHoles(arr) {
18
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
19
+ }
20
+ function _assertThisInitialized(self) {
21
+ if (self === void 0) {
22
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
23
+ }
24
+ return self;
25
+ }
26
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
27
+ try {
28
+ var info = gen[key](arg);
29
+ var value = info.value;
30
+ } catch (error) {
31
+ reject(error);
32
+ return;
33
+ }
34
+ if (info.done) {
35
+ resolve(value);
36
+ } else {
37
+ Promise.resolve(value).then(_next, _throw);
38
+ }
39
+ }
40
+ function _asyncToGenerator(fn) {
41
+ return function() {
42
+ var self = this, args = arguments;
43
+ return new Promise(function(resolve, reject) {
44
+ var gen = fn.apply(self, args);
45
+ function _next(value) {
46
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
47
+ }
48
+ function _throw(err) {
49
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
50
+ }
51
+ _next(undefined);
52
+ });
53
+ };
54
+ }
55
+ function _classCallCheck(instance, Constructor) {
56
+ if (!(instance instanceof Constructor)) {
57
+ throw new TypeError("Cannot call a class as a function");
58
+ }
59
+ }
60
+ function isNativeReflectConstruct() {
61
+ if (typeof Reflect === "undefined" || !Reflect.construct) return false;
62
+ if (Reflect.construct.sham) return false;
63
+ if (typeof Proxy === "function") return true;
64
+ try {
65
+ Date.prototype.toString.call(Reflect.construct(Date, [], function() {}));
66
+ return true;
67
+ } catch (e) {
68
+ return false;
69
+ }
70
+ }
71
+ function _construct(Parent, args, Class) {
72
+ if (isNativeReflectConstruct()) {
73
+ _construct = Reflect.construct;
74
+ } else {
75
+ _construct = function _construct(Parent, args, Class) {
76
+ var a = [
77
+ null
78
+ ];
79
+ a.push.apply(a, args);
80
+ var Constructor = Function.bind.apply(Parent, a);
81
+ var instance = new Constructor();
82
+ if (Class) _setPrototypeOf(instance, Class.prototype);
83
+ return instance;
84
+ };
85
+ }
86
+ return _construct.apply(null, arguments);
87
+ }
88
+ function _getPrototypeOf(o) {
89
+ _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
90
+ return o.__proto__ || Object.getPrototypeOf(o);
91
+ };
92
+ return _getPrototypeOf(o);
93
+ }
94
+ function _inherits(subClass, superClass) {
95
+ if (typeof superClass !== "function" && superClass !== null) {
96
+ throw new TypeError("Super expression must either be null or a function");
97
+ }
98
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
99
+ constructor: {
100
+ value: subClass,
101
+ writable: true,
102
+ configurable: true
103
+ }
104
+ });
105
+ if (superClass) _setPrototypeOf(subClass, superClass);
106
+ }
107
+ function _instanceof(left, right) {
108
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
109
+ return !!right[Symbol.hasInstance](left);
110
+ } else {
111
+ return left instanceof right;
112
+ }
113
+ }
114
+ function _interopRequireDefault(obj) {
115
+ return obj && obj.__esModule ? obj : {
116
+ default: obj
117
+ };
118
+ }
119
+ function _isNativeFunction(fn) {
120
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
121
+ }
122
+ function _iterableToArray(iter) {
123
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
124
+ }
125
+ function _nonIterableSpread() {
126
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
127
+ }
128
+ function _possibleConstructorReturn(self, call) {
129
+ if (call && (_typeof(call) === "object" || typeof call === "function")) {
130
+ return call;
131
+ }
132
+ return _assertThisInitialized(self);
133
+ }
134
+ function _setPrototypeOf(o, p) {
135
+ _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
136
+ o.__proto__ = p;
137
+ return o;
138
+ };
139
+ return _setPrototypeOf(o, p);
140
+ }
141
+ function _toConsumableArray(arr) {
142
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
143
+ }
144
+ var _typeof = function(obj) {
145
+ "@swc/helpers - typeof";
146
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
147
+ };
148
+ function _unsupportedIterableToArray(o, minLen) {
149
+ if (!o) return;
150
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
151
+ var n = Object.prototype.toString.call(o).slice(8, -1);
152
+ if (n === "Object" && o.constructor) n = o.constructor.name;
153
+ if (n === "Map" || n === "Set") return Array.from(n);
154
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
155
+ }
156
+ function _wrapNativeSuper(Class) {
157
+ var _cache = typeof Map === "function" ? new Map() : undefined;
158
+ _wrapNativeSuper = function _wrapNativeSuper(Class) {
159
+ if (Class === null || !_isNativeFunction(Class)) return Class;
160
+ if (typeof Class !== "function") {
161
+ throw new TypeError("Super expression must either be null or a function");
162
+ }
163
+ if (typeof _cache !== "undefined") {
164
+ if (_cache.has(Class)) return _cache.get(Class);
165
+ _cache.set(Class, Wrapper);
166
+ }
167
+ function Wrapper() {
168
+ return _construct(Class, arguments, _getPrototypeOf(this).constructor);
169
+ }
170
+ Wrapper.prototype = Object.create(Class.prototype, {
171
+ constructor: {
172
+ value: Wrapper,
173
+ enumerable: false,
174
+ writable: true,
175
+ configurable: true
176
+ }
177
+ });
178
+ return _setPrototypeOf(Wrapper, Class);
179
+ };
180
+ return _wrapNativeSuper(Class);
181
+ }
182
+ function _isNativeReflectConstruct() {
183
+ if (typeof Reflect === "undefined" || !Reflect.construct) return false;
184
+ if (Reflect.construct.sham) return false;
185
+ if (typeof Proxy === "function") return true;
186
+ try {
187
+ Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
188
+ return true;
189
+ } catch (e) {
190
+ return false;
191
+ }
192
+ }
193
+ function _createSuper(Derived) {
194
+ var hasNativeReflectConstruct = _isNativeReflectConstruct();
195
+ return function _createSuperInternal() {
196
+ var Super = _getPrototypeOf(Derived), result;
197
+ if (hasNativeReflectConstruct) {
198
+ var NewTarget = _getPrototypeOf(this).constructor;
199
+ result = Reflect.construct(Super, arguments, NewTarget);
200
+ } else {
201
+ result = Super.apply(this, arguments);
202
+ }
203
+ return _possibleConstructorReturn(this, result);
204
+ };
205
+ }
206
+ var __generator = (void 0) && (void 0).__generator || function(thisArg, body) {
207
+ var f, y, t, g, _ = {
208
+ label: 0,
209
+ sent: function() {
210
+ if (t[0] & 1) throw t[1];
211
+ return t[1];
212
+ },
213
+ trys: [],
214
+ ops: []
215
+ };
216
+ return g = {
217
+ next: verb(0),
218
+ "throw": verb(1),
219
+ "return": verb(2)
220
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
221
+ return this;
222
+ }), g;
223
+ function verb(n) {
224
+ return function(v) {
225
+ return step([
226
+ n,
227
+ v
228
+ ]);
229
+ };
230
+ }
231
+ function step(op) {
232
+ if (f) throw new TypeError("Generator is already executing.");
233
+ while(_)try {
234
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
235
+ if (y = 0, t) op = [
236
+ op[0] & 2,
237
+ t.value
238
+ ];
239
+ switch(op[0]){
240
+ case 0:
241
+ case 1:
242
+ t = op;
243
+ break;
244
+ case 4:
245
+ _.label++;
246
+ return {
247
+ value: op[1],
248
+ done: false
249
+ };
250
+ case 5:
251
+ _.label++;
252
+ y = op[1];
253
+ op = [
254
+ 0
255
+ ];
256
+ continue;
257
+ case 7:
258
+ op = _.ops.pop();
259
+ _.trys.pop();
260
+ continue;
261
+ default:
262
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
263
+ _ = 0;
264
+ continue;
265
+ }
266
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
267
+ _.label = op[1];
268
+ break;
269
+ }
270
+ if (op[0] === 6 && _.label < t[1]) {
271
+ _.label = t[1];
272
+ t = op;
273
+ break;
274
+ }
275
+ if (t && _.label < t[2]) {
276
+ _.label = t[2];
277
+ _.ops.push(op);
278
+ break;
279
+ }
280
+ if (t[2]) _.ops.pop();
281
+ _.trys.pop();
282
+ continue;
283
+ }
284
+ op = body.call(thisArg, _);
285
+ } catch (e) {
286
+ op = [
287
+ 6,
288
+ e
289
+ ];
290
+ y = 0;
291
+ } finally{
292
+ f = t = 0;
293
+ }
294
+ if (op[0] & 5) throw op[1];
295
+ return {
296
+ value: op[0] ? op[1] : void 0,
297
+ done: true
298
+ };
299
+ }
300
+ };
301
+ var EndError = /*#__PURE__*/ function(Error1) {
302
+ "use strict";
303
+ _inherits(EndError, Error1);
304
+ var _super = _createSuper(EndError);
305
+ function EndError(value) {
306
+ _classCallCheck(this, EndError);
307
+ var _this;
308
+ _this = _super.call(this);
309
+ _this.value = value;
310
+ return _this;
311
+ }
312
+ return EndError;
313
+ }(_wrapNativeSuper(Error));
314
+ // The input can also be a promise, so we await it.
315
+ var testElement = function() {
316
+ var _ref = _asyncToGenerator(function(element, tester) {
317
+ return __generator(this, function(_state) {
318
+ switch(_state.label){
319
+ case 0:
320
+ return [
321
+ 4,
322
+ element
323
+ ];
324
+ case 1:
325
+ return [
326
+ 2,
327
+ tester.apply(void 0, [
328
+ _state.sent()
329
+ ])
330
+ ];
331
+ }
332
+ });
333
+ });
334
+ return function testElement(element, tester) {
335
+ return _ref.apply(this, arguments);
336
+ };
337
+ }();
338
+ // The input can also be a promise, so we `Promise.all()` them both.
339
+ var finder = function() {
340
+ var _ref = _asyncToGenerator(function(element) {
341
+ var values;
342
+ return __generator(this, function(_state) {
343
+ switch(_state.label){
344
+ case 0:
345
+ return [
346
+ 4,
347
+ Promise.all(element)
348
+ ];
349
+ case 1:
350
+ values = _state.sent();
351
+ if (values[1] === true) {
352
+ throw new EndError(values[0]);
353
+ }
354
+ return [
355
+ 2,
356
+ false
357
+ ];
358
+ }
359
+ });
360
+ });
361
+ return function finder(element) {
362
+ return _ref.apply(this, arguments);
363
+ };
364
+ }();
365
+ function pLocate(iterable, tester) {
366
+ return _pLocate.apply(this, arguments);
367
+ }
368
+ function _pLocate() {
369
+ _pLocate = _asyncToGenerator(function(iterable, tester) {
370
+ var ref, _concurrency, concurrency, _preserveOrder, preserveOrder, limit, items, checkLimit, error;
371
+ var _arguments = arguments;
372
+ return __generator(this, function(_state) {
373
+ switch(_state.label){
374
+ case 0:
375
+ ref = _arguments.length > 2 && _arguments[2] !== void 0 ? _arguments[2] : {}, _concurrency = ref.concurrency, concurrency = _concurrency === void 0 ? Number.POSITIVE_INFINITY : _concurrency, _preserveOrder = ref.preserveOrder, preserveOrder = _preserveOrder === void 0 ? true : _preserveOrder;
376
+ limit = (0, _pLimit.default)(concurrency);
377
+ items = _toConsumableArray(iterable).map(function(element) {
378
+ return [
379
+ element,
380
+ limit(testElement, element, tester)
381
+ ];
382
+ });
383
+ checkLimit = (0, _pLimit.default)(preserveOrder ? 1 : Number.POSITIVE_INFINITY);
384
+ _state.label = 1;
385
+ case 1:
386
+ _state.trys.push([
387
+ 1,
388
+ 3,
389
+ ,
390
+ 4
391
+ ]);
392
+ return [
393
+ 4,
394
+ Promise.all(items.map(function(element) {
395
+ return checkLimit(finder, element);
396
+ }))
397
+ ];
398
+ case 2:
399
+ _state.sent();
400
+ return [
401
+ 3,
402
+ 4
403
+ ];
404
+ case 3:
405
+ error = _state.sent();
406
+ if (_instanceof(error, EndError)) {
407
+ return [
408
+ 2,
409
+ error.value
410
+ ];
411
+ }
412
+ throw error;
413
+ case 4:
414
+ return [
415
+ 2
416
+ ];
417
+ }
418
+ });
419
+ });
420
+ return _pLocate.apply(this, arguments);
421
+ }
package/license ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@common.js/p-locate",
3
+ "version": "6.0.0",
4
+ "description": "Get the first fulfilled promise that satisfies the provided testing function",
5
+ "license": "MIT",
6
+ "repository": "etienne-martin/common.js",
7
+ "funding": "https://github.com/sponsors/sindresorhus",
8
+ "type": "commonjs",
9
+ "engines": {
10
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
11
+ },
12
+ "scripts": {
13
+ "test": "xo && ava && tsd"
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "index.d.ts"
18
+ ],
19
+ "dependencies": {
20
+ "@common.js/p-limit": "^4.0.0"
21
+ },
22
+ "devDependencies": {
23
+ "ava": "^3.15.0",
24
+ "delay": "^5.0.0",
25
+ "in-range": "^3.0.0",
26
+ "time-span": "^5.0.0",
27
+ "tsd": "^0.17.0",
28
+ "xo": "^0.44.0"
29
+ },
30
+ "homepage": "https://github.com/etienne-martin/common.js#readme",
31
+ "main": "./index.js"
32
+ }
package/readme.md ADDED
@@ -0,0 +1,91 @@
1
+ # p-locate
2
+
3
+ > Get the first fulfilled promise that satisfies the provided testing function
4
+
5
+ Think of it like an async version of [`Array#find`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find).
6
+
7
+ ## Install
8
+
9
+ ```
10
+ $ npm install p-locate
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ Here we find the first file that exists on disk, in array order.
16
+
17
+ ```js
18
+ import {pathExists} from 'path-exists';
19
+ import pLocate from 'p-locate';
20
+
21
+ const files = [
22
+ 'unicorn.png',
23
+ 'rainbow.png', // Only this one actually exists on disk
24
+ 'pony.png'
25
+ ];
26
+
27
+ const foundPath = await pLocate(files, file => pathExists(file));
28
+
29
+ console.log(foundPath);
30
+ //=> 'rainbow'
31
+ ```
32
+
33
+ *The above is just an example. Use [`locate-path`](https://github.com/sindresorhus/locate-path) if you need this.*
34
+
35
+ ## API
36
+
37
+ ### pLocate(input, tester, options?)
38
+
39
+ Returns a `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`.
40
+
41
+ #### input
42
+
43
+ Type: `Iterable<Promise | unknown>`
44
+
45
+ An iterable of promises/values to test.
46
+
47
+ #### tester(element)
48
+
49
+ Type: `Function`
50
+
51
+ This function will receive resolved values from `input` and is expected to return a `Promise<boolean>` or `boolean`.
52
+
53
+ #### options
54
+
55
+ Type: `object`
56
+
57
+ ##### concurrency
58
+
59
+ Type: `number`\
60
+ Default: `Infinity`\
61
+ Minimum: `1`
62
+
63
+ The number of concurrently pending promises returned by `tester`.
64
+
65
+ ##### preserveOrder
66
+
67
+ Type: `boolean`\
68
+ Default: `true`
69
+
70
+ Preserve `input` order when searching.
71
+
72
+ Disable this to improve performance if you don't care about the order.
73
+
74
+ ## Related
75
+
76
+ - [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently
77
+ - [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently
78
+ - [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled
79
+ - [More…](https://github.com/sindresorhus/promise-fun)
80
+
81
+ ---
82
+
83
+ <div align="center">
84
+ <b>
85
+ <a href="https://tidelift.com/subscription/pkg/npm-p-locate?utm_source=npm-p-locate&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
86
+ </b>
87
+ <br>
88
+ <sub>
89
+ Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
90
+ </sub>
91
+ </div>