UNPKG

prray

Version:

'Promisified' Array, it compatible with the original Array but comes with async versions of native Array methods, such as `mapAsync`, `filterAsync`, `reduceAsync`, `sortAsync`, `findAsync`, `findIndexAsync`, `everyAsync`, `someAsync`, `forEachAsync`...

307 lines (272 loc) 11.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const prraypromise_1 = require("./prraypromise"); const methods = require("./methods"); // TODO: thisArg class Prray extends Array { /** _Compatible with [`Array.of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of) but returns a Prray instance._ The Prray.of() method creates a new Prray instance from a variable number of arguments, regardless of number or type of the arguments. ```javascript const prr = Prray.of(1, 2, 3, 4) ``` * @param args */ static of(...args) { return Prray.from(args); } /** The Prray.isArray() method determines whether the passed value is a Prray instance. ```javascript Prray.isPrray([1, 2, 3]) // false Prray.isPrray(new Prray(1, 2, 3)) // true ``` * @param obj */ static isPrray(obj) { return obj instanceof Prray; } static from(arrayLike, mapFunc, thisArg) { const arr = mapFunc === undefined ? super.from(arrayLike) : super.from(arrayLike, mapFunc, thisArg); const prr = new Prray(); for (let i = arr.length - 1; i >= 0; i--) { prr[i] = arr[i]; } return prr; } /** The Prray.delay() method returns a promise (`PrrayPromise` exactly) that will be resolved after given ms milliseconds. ```javascript await Prray.delay(1000) // resolve after 1 second const prr = Prray.from([1,2,3]) await prr .mapAsync(action1) .delay(500) // delay 500ms between two iterations .forEach(action2) ``` * @param ms */ static delay(ms) { const prray = new Prray(); return new prraypromise_1.PrrayPromise(resolve => setTimeout(() => resolve(prray), ms)); } constructor(...args) { super(...args); } /** _Think of it as an async version of method `map`_ The mapAsync() method returns a promise (`PrrayPromise` exactly) that resolved with a new prray with the resolved results of calling a provided async function on every element in the calling prray, or rejected immediately if any of the promises reject. The provided async function is called on every element concurrently. You may optionally specify a concurrency limit. - `func(currentValue, index, prray)` - options - `concurrency` Number of concurrently pending promises returned by provided function. Default: `Infinity` ```javascript const urls = Prray.from(urlArray) const jsons = await urls.mapAsync(fetch).mapAsync(res => res.json()) await jsons.mapAsync(insertToDB, { concurrency: 2 }) ``` * @param func * @param opts */ mapAsync(func, opts) { const promise = methods.mapAsync(this, func, opts); return prraypromise_1.prraypromise(promise.then(arr => Prray.from(arr))); } map(func) { return _ensurePrray(methods.map(this, func)); } /** _Think of it as an async version of method `filter`_ The filterAsync() method returns a promise (`PrrayPromise` exactly) that resolved with a new prray with all elements that pass the test implemented by the provided async function, or rejected immediately if any of the promises reject. The provided async function is called on every element concurrently. You may optionally specify a concurrency limit. - `func(currentValue, index, prray)` - options - `concurrency` Number of concurrently pending promises returned by provided function. Default: `Infinity` ```javascript const files = Prray.from(fileArray) await files.filterAsync(isExisted).mapAsync(removeFile) await files.filterAsync(isExisted, { concurrency: 2 }) ``` * @param func * @param opts */ filterAsync(func, opts) { const promise = methods.filterAsync(this, func, opts); return prraypromise_1.prraypromise(promise.then(arr => Prray.from(arr))); } filter(func) { return _ensurePrray(methods.filter(this, func)); } reduceAsync(func, initialValue) { const promise = methods.reduceAsync(this, func, initialValue); return promise; } reduce(func, initialValue) { return methods.reduce(this, func, initialValue); } reduceRightAsync(func, initialValue) { const promise = methods.reduceRightAsync(this, func, initialValue); return promise; } reduceRight(func, initialValue) { return methods.reduceRight(this, func, initialValue); } /** _Think of it as an async version of method `sort`_ The sortAsync() method sorts the elements of a prray in place and returns a promise (`PrrayPromise` exactly) resolved with the sorted prray. The provided function can be an async function that returns a promise resolved with a number. ```javascript const students = Prray.from(idArray) const rank = await students.sortAsync((a, b) => { const scoreA = await getScore(a) const scoreB = await getScore(b) return scoreA - scoreB }) ``` * @param func */ sortAsync(func) { const promise = methods.sortAsync(this, func); return prraypromise_1.prraypromise(promise); } /** _Think of it as an async version of method `find`_ The findAsync() method returns a promise (`PrrayPromise` exactly) resolved with the first element in the prray that satisfies the provided async testing function. ```javascript const workers = Prray.from(workerArray) const unhealthy = await workers.findAsync(checkHealth) ``` * @param func */ findAsync(func) { return methods.findAsync(this, func); } find(func) { return methods.find(this, func); } /** _Think of it as an async version of method `findIndex`_ The findIndexAsync() method returns a promise (`PrrayPromise` exactly) resolved with the index of the first element in the prray that satisfies the provided async testing function. Otherwise, it returns promise resolved with -1, indicating that no element passed the test. ```javascript const workers = Prray.from(workerArray) const ix = await workers.findIndexAsync(checkHealth) const unhealthy = workers[ix] ``` */ findIndexAsync(func) { return methods.findIndexAsync(this, func); } findIndex(func) { return methods.findIndex(this, func); } /** _Think of it as an async version of method `every`_ The everyAsync() method tests whether all elements in the prray pass the test implemented by the provided async function. It returns a promise (`PrrayPromise` exactly) that resolved with a Boolean value, or rejected immediately if any of the promises reject. The provided async function is called on every element concurrently. You may optionally specify a concurrency limit. - `func(currentValue, index, prray)` - options - `concurrency` Number of concurrently pending promises returned by provided function. Default: `Infinity` ```javascript const filenames = Prray.from(fileNameArray) const isAllFileExisted = await filenames.everyAsync(isExisted) if (isAllFileExisted) { // do some things } ``` */ everyAsync(func, opts) { return methods.everyAsync(this, func, opts); } every(func) { return methods.every(this, func); } /** _Think of it as an async version of method `some`_ The some() method tests whether at least one element in the prray passes the test implemented by the provided async function. It returns a promise (`PrrayPromise` exactly) that resolved with Boolean value, or rejected immediately if any of the promises reject. The provided async function is called on every element concurrently. You may optionally specify a concurrency limit. - `func(currentValue, index, prray)` - options - `concurrency` Number of concurrently pending promises returned by provided function. Default: `Infinity` ```javascript const filenames = Prray.from(fileNameArray) const hasExistedFile = await filenames.someAsync(isExisted) if (hasExistedFile) { // do some things } ``` */ someAsync(func, opts) { return methods.someAsync(this, func, opts); } some(func) { return methods.some(this, func); } /** _Think of it as an async version of method `forEach`_ The forEachAsync() method executes a provided async function once for each prray element concurrently. It returns a promise (`PrrayPromise` exactly) that resolved after all iteration promises resolved, or rejected immediately if any of the promises reject. The provided async function is called on every element concurrently. You may optionally specify a concurrency limit. - `func(currentValue, index, prray)` - options - `concurrency` Number of concurrently pending promises returned by provided function. Default: `Infinity` ```javascript const emails = Prray.from(emailArray) await emails.forEachAsync(sendAsync) await emails.forEachAsync(sendAsync, { concurrency: 20 }) ``` * @param func * @param opts */ forEachAsync(func, opts) { return methods.forEachAsync(this, func, opts); } forEach(func) { return methods.forEach(this, func); } slice(start, end) { const result = super.slice(start, end); return _ensurePrray(result); } concat(...items) { return _ensurePrray(super.concat(...items)); } reverse() { return super.reverse(); } splice(start, deleteCount, ...items) { // Why? If pass parameter deleteCount as undefined directly, the delete count will be zero actually :( const result = deleteCount === undefined ? super.splice(start) : super.splice(start, deleteCount, ...items); return _ensurePrray(result); } /** The toArray() method returns a new normal array with every element in the prray. ```javascript const prr = new Prray(1, 2, 3) prr.toArray() // [1,2,3] ``` */ toArray() { return [...this]; } /** The delay() method returns a promise (`PrrayPromise` exactly) that will be resolved with current prray instance after given ms milliseconds. ```javascript const emails = Prray.from(emailArray) await emails .mapAsync(registerReceiver) .delay(1000) .forEachAsync(send) ``` */ delay(ms) { return new prraypromise_1.PrrayPromise(resolve => setTimeout(() => resolve(this), ms)); } } exports.default = Prray; function _ensurePrray(arr) { if (arr instanceof Prray) { return arr; } else { return Prray.from(arr); } } exports._ensurePrray = _ensurePrray;