Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

"Promisified" Array, it compatible with the original Array but comes with async versions of native Array methods

License

NotificationsYou must be signed in to change notification settings

Bin-Huang/prray

Repository files navigation

TravisPackage versionCoverage StatusInstall sizeLicense

Prray -- "Promisified" Array, it compatible with the original Array but comes with async versions of native Array methods, such as mapAsync, filterAsync, everyAsync...

  • compatible with normal array
  • comes with async versions of native Array methods
  • supportsmethod chaining with normal and async methods
  • supports concurrency limit
  • it works without any prototype pollution
  • zero-dependency, it can run on both browser and Node.js
  • well-tested, well-documented
importPrrayfrom'prray'// 1) createconsturls=Prray.from(['www.google.com','npmjs.org'])// 2) async methodletresponses=awaiturls.mapAsync(fetch)// 3) method chaining with both normal and async methodsawaiturls.concat(['github.com','wikipedia.org']).mapAsync(request).filter(isValidHtml).forEachAsync(saveToDB)// 4) concurrency limitresponses=awaiturls.mapAsync(fetch,{concurrency:10})

Prray aims to replace the original Array in some cases for convenience 😜

Install

npm

npm install prray --save

yarn

yarn add prray

Compatibility with normal Array

Prray is compatible with normal array. That means you can safely replace normal Array with Prray. And there area lots of unit tests for prray to test compatibility with normal array.

importPrrayfrom'prray'constarr=[1,2,3]constprr=Prray.from(arr)prr[0]// 1prr[prr.length-1]// 3prr.length// 3prrinstanceofArray// trueArray.isArray(prr)// trueJSON.stringify(prr)// "[1, 2, 3]"for(constvofprr){console.log(v)}// 1// 2// 3[ ...prr]// [1,2,3]constiterator=prr[Symbol.iterator]()iterator.next().value// 1iterator.next().value// 2iterator.next().value// 3iterator.next().done// true// In typescript, type Prray is compatible with type Arrayfunctionfunc(arr:number[]){returnarr}func(newPrray(1,2,3))

How it work?

Class Prray inherits the original class Array and adds or overrides methods based on it. It works without any prototype pollution and global pollution.

constprr=Prray.from([1,2,3])console.log(prr.mapAsync)// [Function]constarr=[1,2,3]console.log(arr.mapAsync)// [undefined]

Distinguish between prray and normal array

constprr=newPrray(1,2,3)constarr=newArray(1,2,3)Prray.isPrray(prr)// truePrray.isPrray(arr)// falseprrinstanceofPrray// truearrinstanceofPrray// false

Methods

Class Prray

The classPrray. You can think of it as classArray.

importPrrayfrom'prray'constp1=newPrray()constp2=newPrray('a','b')constp3=Prray.from([1,2,3,4])console.log(p2[0])// 'a'

[NOTE]: Insteadnew Prray(), usePrray.from orPrray.of if you want to create a new prray instance with items. Because the class Prray is so compatible with class Array, some "weird" behaviors that exists innew Array() can also occurs: when you callingnew Array(1), you get[ <1 empty item> ] instead of expected[ 1 ].

Static methods of Class Prray

Prray.from(arrayLike)

Compatible withArray.from but returns a Prray instance.

The Prray.from() method creates a new, shallow-copied Prray instance from an array-like or iterable object.

constprr=Prray.from([1,2,3,4])

Prray.of(...args)

Compatible withArray.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.

constprr=Prray.of(1,2,3,4)

Prray.isPrray(obj)

The Prray.isArray() method determines whether the passed value is a Prray instance.

Prray.isPrray([1,2,3])// falsePrray.isPrray(newPrray(1,2,3))// true

Prray.delay(ms)

The Prray.delay() method returns a promise (PrrayPromise exactly) that will be resolved after given ms milliseconds.

awaitPrray.delay(1000)// resolve after 1 secondconstprr=Prray.from([1,2,3])awaitprr.mapAsync(action1).delay(500)// delay 500ms between two iterations.forEach(action2)

Specific methods of Prray instance

Prray.prototype.toArray()

The toArray() method returns a new normal array with every element in the prray.

constprr=newPrray(1,2,3)prr.toArray()// [1,2,3]

Prray.prototype.delay(ms)

The delay() method returns a promise (PrrayPromise exactly) that will be resolved with current prray instance after given ms milliseconds.

constemails=Prray.from(emailArray)awaitemails.mapAsync(registerReceiver).delay(1000).forEachAsync(send)

Prray.prototype.mapAsync(func, options)

Think of it as an async version of methodmap

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
consturls=Prray.from(urlArray)constjsons=awaiturls.mapAsync(fetch).mapAsync(res=>res.json())awaitjsons.mapAsync(insertToDB,{concurrency:2})

Prray.prototype.filterAsync(func, options)

Think of it as an async version of methodfilter

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
constfiles=Prray.from(fileArray)awaitfiles.filterAsync(isExisted).mapAsync(removeFile)awaitfiles.filterAsync(isExisted,{concurrency:2})

Prray.prototype.reduceAsync(func, initialValue)

Think of it as an async version of methodreduce

The reduceAsync() method executes a async reducer function (that you provide) on each element of the prray, resulting in a single output value resolved by a promise (PrrayPromise exactly).

constproductIds=Prray.from(idArray)consttotal=awaitproductIds.reduceAsync(async(total,id)=>{constprice=awaitgetPrice(id)returntotal+price},0)

Prray.prototype.reduceRightAsync(func, initialValue)

Think of it as an async version of methodreduceRight

The reduceRightAsync() method applies an async function against an accumulator and each value of the prray (from right-to-left) to reduce it to a single value.

constproductIds=Prray.from(idArray)consttotal=awaitproductIds.reduceRightAsync(async(total,id)=>{constprice=awaitgetPrice(id)returntotal+price},0)

Prray.prototype.findAsync(func)

Think of it as an async version of methodfind

The findAsync() method returns a promise (PrrayPromise exactly) resolved with the first element in the prray that satisfies the provided async testing function.

constworkers=Prray.from(workerArray)constunhealthy=awaitworkers.findAsync(checkHealth)

Prray.prototype.findIndexAsync(func)

Think of it as an async version of methodfindIndex

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.

constworkers=Prray.from(workerArray)constix=awaitworkers.findIndexAsync(checkHealth)constunhealthy=workers[ix]

Prray.prototype.everyAsync(func, options)

Think of it as an async version of methodevery

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
constfilenames=Prray.from(fileNameArray)constisAllFileExisted=awaitfilenames.everyAsync(isExisted)if(isAllFileExisted){// do some things}

Prray.prototype.someAsync(func, options)

Think of it as an async version of methodsome

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
constfilenames=Prray.from(fileNameArray)consthasExistedFile=awaitfilenames.someAsync(isExisted)if(hasExistedFile){// do some things}

Prray.prototype.sortAsync(func)

Think of it as an async version of methodsort

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.

conststudents=Prray.from(idArray)constrank=awaitstudents.sortAsync((a,b)=>{constscoreA=awaitgetScore(a)constscoreB=awaitgetScore(b)returnscoreA-scoreB})

Prray.prototype.forEachAsync(func, options)

Think of it as an async version of methodforEach

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
constemails=Prray.from(emailArray)awaitemails.forEachAsync(sendAsync)// orawaitemails.forEachAsync(sendAsync,{concurrency:20})

Other methods of Prray instance (compatible with Array)

Prray.prototype.map(func)

Compatible withArray.prototype.map but returns a Prray instance.

The map() method creates a new prray with the results of calling a provided function on every element in the calling prray.

Prray.prototype.filter(func)

Compatible withArray.prototype.filter but returns a Prray instance.

The filter() method creates a new prray with all elements that pass the test implemented by the provided function.

Prray.prototype.reduce(func, initialValue)

Compatible withArray.prototype.reduce.

The reduce() method executes a reducer function (that you provide) on each element of the prray, resulting in a single output value.

Prray.prototype.reduceRight(func, initialValue)

Compatible withArray.prototype.reduceRight

The reduceRight() method applies a function against an accumulator and each value of the prray (from right-to-left) to reduce it to a single value.

Prray.prototype.find(func)

Compatible withArray.prototype.find

The find() method returns the value of the first element in the prray that satisfies the provided testing function.

Prray.prototype.findIndex(func)

Compatible withArray.prototype.findIndex

The findIndex() method returns the index of the first element in the prray that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.

Prray.prototype.every(func)

Compatible withArray.prototype.every

The every() method tests whether all elements in the prray pass the test implemented by the provided function. It returns a Boolean value.

Prray.prototype.some(func)

Compatible withArray.prototype.some

The some() method tests whether at least one element in the prray passes the test implemented by the provided function. It returns a Boolean value.

Prray.prototype.sort(func)

Compatible withArray.prototype.sort

The sort() method sorts the elements of a prray in place and returns the sorted prray.

Prray.prototype.forEach(func)

Compatible withArray.prototype.forEach

The forEach() method executes a provided function once for each prray element.

Prray.prototype.slice(start, end)

Compatible withArray.prototype.slice but returns a Prray instance

The slice() method returns a shallow copy of a portion of a prray into a new prray object selected from begin to end (end not included) where begin and end represent the index of items in that prray. The original prray will not be modified.

Prray.prototype.includes(value)

Compatible withArray.prototype.includes

The includes() method determines whether a prray includes a certain value among its entries, returning true or false as appropriate.

Prray.prototype.indexOf(value)

Compatible withArray.prototype.indexOf

The indexOf() method returns the first index at which a given element can be found in the prray, or -1 if it is not present.

Prray.prototype.lastIndexOf(value)

Compatible withArray.prototype.lastIndexOf

The lastIndexOf() method returns the last index at which a given element can be found in the prray, or -1 if it is not present. The prray is searched backwards, starting at fromIndex.

Prray.prototype.join(separator)

Compatible withArray.prototype.join

The join() method creates and returns a new string by concatenating all of the elements in a prray (or an array-like object), separated by commas or a specified separator string. If the prray has only one item, then that item will be returned without using the separator.

Prray.prototype.keys()

Compatible withArray.prototype.keys

The keys() method returns a new Array Iterator object that contains the keys for each index in the prray.

Prray.prototype.values()

Compatible withArray.prototype.values

The values() method returns a new Array Iterator object that contains the values for each index in the prray.

Prray.prototype.entries()

Compatible withArray.prototype.entries

The entries() method returns a new Array Iterator object that contains the key/value pairs for each index in the prray.

Prray.prototype.fill(value, start, end)

Compatible withArray.prototype.fill

The fill() method fills (modifies) all the elements of a prray from a start index (default zero) to an end index (default array length) with a static value. It returns the modified prray.

Prray.prototype.concat(arr)

Compatible withArray.prototype.concat but returns a Prray instance

The concat() method is used to merge two or more prrays and arrays. This method does not change the existing prrays, but instead returns a new prray.

Prray.prototype.copyWithin(target, star, end)

Compatible withArray.prototype.copyWithin

The copyWithin() method shallow copies part of a prray to another location in the same prray and returns it without modifying its length.

Prray.prototype.pop()

Compatible withArray.prototype.pop

The pop() method removes the last element from a prray and returns that element. This method changes the length of the prray.

Prray.prototype.push(...elements)

Compatible withArray.prototype.push

The push() method adds one or more elements to the end of a prray and returns the new length of the prray.

Prray.prototype.reverse()

Compatible withArray.prototype.reverse

The reverse() method reverses a prray in place. The first prray element becomes the last, and the last prray element becomes the first.

Prray.prototype.shift()

Compatible withArray.prototype.shift

The shift() method removes the first element from a prray and returns that removed element. This method changes the length of the prray.

Prray.prototype.unshift(...elements)

Compatible withArray.prototype.unshift

The unshift() method adds one or more elements to the beginning of a prray and returns the new length of the prray.

Prray.prototype.splice(start, deleteCount, ...items)

Compatible withArray.prototype.splice but returns a Prray instance.

The splice() method changes the contents of a prray by removing or replacing existing elements and/or adding new elements in place.

Prray.prototype.toString()

Compatible withArray.prototype.toString

The toString() method returns a string representing the specified prray and its elements.

Prray.prototype.toLocaleString()

Compatible withArray.prototype.toLocaleString

The toLocaleString() method returns a string representing the elements of the prray. The elements are converted to Strings using their toLocaleString methods and these Strings are separated by a locale-specific String (such as a comma “,”).

Why notbluebird

Bluebird and prray have different concerns, so it may not be suitable for comparison. If you must compare, can also try:

  1. Prray focuses on arrays, Bluebird focuses on promises
  2. Bluebird has some methods such asmap, but prray has more:findAsync,everyAsync, etc
  3. Prray supports async method chaining, but for bluebird, you have to:Bluebird.map(await Bluebird.map(arr,func1), func2)
  4. Prray is based on native promise implementation, and bluebird provides a good third-party promise implementation

Sponsoring

"Buy Me A Coffee"

License

MIT

About

"Promisified" Array, it compatible with the original Array but comes with async versions of native Array methods

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp