UNPKG

prray

Version:

'Promisified' Array, comes with async method supports(such as mapAsync). And it is compatible with normal array.

97 lines (96 loc) 2.85 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const prraypromise_1 = require("./prraypromise"); const methods = require("./methods"); // TODO: Mutable and Immutable // TODO: thisArg class Prray extends Array { constructor(...args) { super(...args); } static of(...args) { return Prray.from(args); } static isPrray(obj) { return obj instanceof Prray; } static from(arrayLike, mapFunc, thisArg) { const arr = arrayLike instanceof Array && mapFunc === undefined ? 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; } mapAsync(func) { const promise = methods.map(this, func); return prraypromise_1.prraypromise(promise.then(arr => Prray.from(arr))); } filterAsync(func) { const promise = methods.filter(this, func); return prraypromise_1.prraypromise(promise.then(arr => Prray.from(arr))); } reduceAsync(callback, initialValue) { return methods.reduce(this, callback, initialValue); } reduceRightAsync(callback, initialValue) { return methods.reduceRight(this, callback, initialValue); } sortAsync(func) { const promise = methods.sort(this, func); return prraypromise_1.prraypromise(promise.then(arr => Prray.from(arr))); } findAsync(func) { return methods.find(this, func); } findIndexAsync(func) { return methods.findIndex(this, func); } everyAsync(func) { return methods.every(this, func); } someAsync(func) { return methods.some(this, func); } forEachAsync(func) { return methods.forEach(this, func); } slice(start, end) { const result = super.slice(start, end); return _ensurePrray(result); } map(func) { return _ensurePrray(super.map(func)); } filter(func) { return _ensurePrray(super.filter(func)); } 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 = arguments.length >= 2 ? super.splice(start, deleteCount, ...items) : super.splice(start); return _ensurePrray(result); } toArray() { return [...this]; } } exports.Prray = Prray; function prray(arr) { return Prray.from(arr); } exports.prray = prray; function _ensurePrray(arr) { if (arr instanceof Prray) { return arr; } else { return Prray.from(arr); } } exports._ensurePrray = _ensurePrray;