Skip to content
"Promisified" Array, compatible with normal array, but comes with async method supports.
TypeScript
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src Add tests for immutable methods Oct 7, 2019
test
.gitignore
.npmignore
.prettierrc
.travis.yml
LICENSE.md
README.md
TODO
package-lock.json
package.json
tsconfig.json

README.md

Travis Package version Coverage Status Install size License

Prray -- "Promisified" Array, compatible with normal array, but comes with async method supports.

  • compatible with normal array
  • comes with async method supports, such as mapAsync
  • supports real async method chaining
  • supports concurrency limit
  • well-tested
  • zero-dependency

Prray aims to replace normal Array in some cases for convenience 😄😜

import { prray } from 'prray'
;(async () => {
  // Create a new "prray" from normal array
  const prr = prray(['www.google.com', 'npmjs.org'])

  // Mapping async function with concurrency limit
  const responses = await prr.mapAsync(fetch, { concurrency: 10 })

  // Async method chaining 🚀
  const htmls = await prr.mapAsync(fetch).mapAsync(r => r.text())

  // Method chaining with async and common methods
  await prr
    .map(commonFunc)
    .sortAsync(asyncFunc)
    .concat(['github.com', 'wikipedia.org'])
    .reverse()
    .splice(1, 2)
    .reduceAsync(asyncFunc2)
})()

Install

npm

npm install prray --save

yarn

yarn add prray

Compatibility with normal Array

import { prray, Prray } from 'prray'

const arr = [1, 2, 3]
const prr = prray(arr)

prr[0] // 1
prr[prr.length - 1] // 3
prr.length // 3

prr instanceof Array // true
Array.isArray(prr) // true

JSON.stringify(prr) // "[1, 2, 3]"

for (const v of prr) {
  console.log(v)
}
// 1
// 2
// 3

;[...prr] // [1,2,3]

const iterator = prr[Symbol.iterator]()
iterator.next().value // 1
iterator.next().value // 2
iterator.next().value // 3
iterator.next().done // true

function func(arr: number[]) {
  return arr
}
func(new Prray(1, 2, 3)) // Type Prray is compatible with type Array in typescript

There are a lots of unit tests for prray to test compatibility with normal array.

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.

Distinguish between prray and normal array

const prr = new Prray(1, 2, 3)
const arr = new Array(1, 2, 3)

Prray.isPrray(prr) // true
Prray.isPrray(arr) // false

prr instanceof Prray // true
arr instanceof Prray // false

Methods

Package methods

prray(array)

The prray() method creates and returns a new Prray instance with every element in the array.

import { prray } from 'prray'

const prr = prray([1, 2, 3])
console.log(prr[0]) // 1

new Prray()

The class Prray. You can think of it as class Array.

import { Prray } from 'prray'

const p1 = new Prray()
const p2 = new Prray(1)
const p3 = new Prray('a', 'b')

console.log(p3[0]) // 'a'

Instead new Prray(), use methods prray, Prray.from or Prray.of if you want to create a new prray instance. Because the class Prray is so compatible with class Array, some "weird" behaviors that exists in new Array() can also occurs: when you calling new Array(1), you get [ <1 empty item> ] instead of expected [ 1 ].

Static methods of Class Prray

Prray.from(arrayLike)

Compatible with Array.from but returns a Prray instance.

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

import { Prray } from 'prray'

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

Prray.of(...args)

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

import { Prray } from 'prray'

const prr = Prray.of(1, 2, 3, 4)

Prray.isPrray(obj)

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

import { Prray } from 'prray'

Prray.isPrray([1, 2, 3]) // false
Prray.isPrray(new Prray(1, 2, 3)) // true

Specific methods of Prray instance

Prray.prototype.toArray()

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

const prr = new Prray(1, 2, 3)

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

Prray.prototype.mapAsync(func, options)

Think of it as an async version of method map

The mapAsync() method returns a promise resolved with a new prray with the resolved results of calling a provided async function on every element in the calling prray.

The provided async function is called on every element concurrently.

  • func(currentValue, index, prray)
  • options
    • concurrency Number of concurrently pending promises returned by provided function. Default: Infinity
const urls = prray([
  /* urls */
])

const jsons = await urls.mapAsync(fetch).mapAsync(res => res.json())

await jsons.mapAsync(insertToDB, { concurrency: 2 })

Prray.prototype.filterAsync(func, options)

Think of it as an async version of method filter

The filterAsync() method returns a promise resolved with a new prray with all elements that pass the test implemented by the provided async function.

The provided async function is called on every element concurrently.

  • func(currentValue, index, prray)
  • options
    • concurrency Number of concurrently pending promises returned by provided function. Default: Infinity
const files = prray([
  /* filenames */
])

await files.filterAsync(isExisted).mapAsync(removeFile)

await files.filterAsync(isExisted, { concurrency: 2 })

Prray.prototype.reduceAsync(func, initialValue)

Think of it as an async version of method reduce

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.

const productIds = prray([
  /* ids */
])

const total = await productIds.reduceAsync(async (total, id) => {
  const price = await getPrice(id)
  return total + price
}, 0)

Prray.prototype.reduceRightAsync(func, initialValue)

Think of it as an async version of method reduceRight

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.

const productIds = prray([
  /* ids */
])

const total = await productIds.reduceRightAsync(async (total, id) => {
  const price = await getPrice(id)
  return total + price
}, 0)

Prray.prototype.findAsync(func)

Think of it as an async version of method find

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

const workers = prray([
  /* workers */
])

const unhealthy = await workers.findAsync(checkHealth)

Prray.prototype.findIndexAsync(func)

Think of it as an async version of method findIndex

The findIndexAsync() method returns a promise 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.

const workers = prray([
  /* workers */
])
const ix = await workers.findIndexAsync(checkHealth)
const unhealthy = workers[ix]

Prray.prototype.everyAsync(func, options)

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 resolved with a Boolean value.

The provided async function is called on every element concurrently.

  • func(currentValue, index, prray)
  • options
    • concurrency Number of concurrently pending promises returned by provided function. Default: Infinity
const filenames = prray([
  /* filenames */
])

const isAllFileExisted = await filenames.everyAsync(isExisted)
if (isAllFileExisted) {
  // do some things
}

Prray.prototype.someAsync(func, options)

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 resolved with Boolean value.

The provided async function is called on every element concurrently.

  • func(currentValue, index, prray)
  • options
    • concurrency Number of concurrently pending promises returned by provided function. Default: Infinity
const filenames = prray([
  /* filenames */
])

const hasExistedFile = await filenames.someAsync(isExisted)
if (hasExistedFile) {
  // do some things
}

Prray.prototype.sortAsync(func)

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 resolved with the sorted prray. The provided function can be an async function that returns a promise resolved with a number.

const students = prray([/* ids */])

const rank = await students.sortAsync((a, b) => {
  const scoreA = await getScore(a)
  const scoreB = await getScore(b)
  return scoreA - scoreB
})

Prray.prototype.forEachAsync(func, options)

Think of it as an async version of method forEach

The forEachAsync() method executes a provided async function once for each prray element concurrently and returns a promise resolved after all iteration promises resolved.

  • func(currentValue, index, prray)
  • options
    • concurrency Number of concurrently pending promises returned by provided function. Default: Infinity
const emails = prray([
  /* emails */
])
await emails.forEachAsync(sendAsync)

// or
await emails.forEachAsync(sendAsync, { concurrency: 20 })

Other methods of Prray instance (compatible with Array)

Prray.prototype.map(func)

Compatible with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.prototype.sort

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

Prray.prototype.forEach(func)

Compatible with Array.prototype.forEach

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

Prray.prototype.slice(start, end)

Compatible with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.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 with Array.prototype.toString

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

Prray.prototype.toLocaleString()

Compatible with Array.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 not bluebird

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 as map, 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

License

MIT

You can’t perform that action at this time.