npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

array-async-utils

v1.0.1

Published

Array map, flatMap, filter, reduce, etc. with async callback and predicate

Downloads

3

Readme

NPM Version GitHub License npm bundle size

Small set of utility functions to perform async array mapping, filtering and reducing.

How to install

Simply install the array-async-utils from npm.

You can use one of the following commands, or the equivalent command of the package manager of your choice.

  npm install array-async-utils
  yarn add array-async-utils

Usage

These funcitons accepts the input array as first paramenter, while the arguments, types and returned value resemble as much as possible the ones of the equivalent Array method.

asyncMap

Same behaviour as Array.map, but supports an async callback: all async callbacks are executed in parallel.

If one callback throws an error, the whole map function throws as well.

import { asyncMap } from 'array-async-utils';

import { getUser } from 'apis/user';

const yourFunction = async () => {
  const userIds = ['92f9e7a1', '59ef0d84', '6b6cafba'];
  const users = await asyncMap(userIds, async (userId) => {
    const { user } = await getUser(userId);
    return user;
  });
};
Specify mapped element type
// ...
const array = [1, 2, 3];
const mappedArray = await asyncMap<typeof array, MappedElement>(
  array,
  async (element) => {
    // ...
  }
);
// ^^^ callback will expect Promise<MappedElement> return type, and mappedArray will be of type MappedElement[]

(^ back to index)

asyncSerialMap

Same as asyncMap, but async callbacks are executed in series: each one is executed when the previous is finished.

Even if not common, it can be useful when some rece condition might happen in the async callback.

If one callback throws an error, the whole map function throws as well.

import { asyncSerialMap } from 'array-async-utils';

import { getUser } from 'apis/user';
import { userCache } from 'cache/user';

const yourFunction = async () => {
  const userIds = ['92f9e7a1', '59ef0d84', '6b6cafba'];
  const users = await asyncSerialMap(userIds, async (userId) => {
    const cachedUser = userCache.get(userId);
    if (cachedUser) {
      return cachedUser;
    }
    const { user } = await getUser(userId);
    cachedUser.set(userId, user);
    return user;
  });
};
Specify mapped element type
// ...
const array = [1, 2, 3];
const mappedArray = await asyncMap<typeof array, MappedElement>(
  array,
  async (element) => {
    // ...
  }
);
// ^^^ callback will expect Promise<MappedElement> return type, and mappedArray will be of type MappedElement[]

(^ back to index)

asyncFlatMap

Same behaviour as Array.flatMap, but supports an async callback: all async callbacks are executed in parallel.

If one callback throws an error, the whole map function throws as well.

import { asyncFlatMap } from 'array-async-utils';

import { getUsersByGroup } from 'apis/user';

const yourFunction = async () => {
  const userGroups = ['groupA', 'groupB', 'groupC'];
  const users = await asyncFlatMap(userIds, async (userId) => {
    const { groupUsers } = await getUsersByGroup(userId);
    return groupUsers;
  });
};
Specify mapped element type
// ...
const array = [1, 2, 3];
const mappedArray = await asyncFlatMap<typeof array, MappedElement>(
  array,
  async (element) => {
    // ...
  }
);
// ^^^ callback will expect Promise<MappedElement | MappedElement[]> return type, and mappedArray will be of type MappedElement[]

(^ back to index)

asyncFilter

Same behaviour as Array.filter, but supports an async predicate: all async predicates are executed in parallel.

If one callback throws an error, the whole filter function throws as well.

IMPORTANT: unfortunately typescript doesn't support type guards with async function, so if you need to narrow down the type of the filtered array, please use the generics as described below

import { asyncFilter } from 'array-async-utils';

import { getUserStatus } from 'apis/user';

const yourFunction = async () => {
  const userIds = ['asyncFilter', '59ef0d84', '6b6cafba'];
  const users = await asyncFilter(userIds, async (userId) => {
    const { isOnline } = await getUserStatus(userId);
    return isOnline;
  });
};
Filtered array type narrowing
// ...
const array = [1, 2, 3, undefined];
const filteredArray = await asyncFilter<typeof array, number>(
  array,
  async (element) => {
    // ...
  }
);
// ^^^ filteredArray will be of type number[]

(^ back to index)

asyncReduce

Same behaviour as Array.reduce, but supports an async callback. Async callbacks are executed in series: each one is executed when the previous is finished.

If one callback throws an error, the whole map function throws as well.

import { asyncReduce } from 'array-async-utils';

import { getArticleStats } from 'apis/user';

const yourFunction = async () => {
  const articleIds = ['92f9e7a1', '59ef0d84', '6b6cafba'];
  const totalInteractions = await asyncReduce(
    articleIds,
    async (accumulator, articleId) => {
      const { articleInteractions } = getArticleStats(articleId);
      return accumulator + articleInteractions;
    },
    0
  );
};
Specify initialValue/accumulator and reduced value type
// ...
const array = [1, 2, 3];
const reducedValue = await asyncReduce<typeof array, Record<string, number>>(
  array,
  async (accumulator, element) => {
    // ...
  },
  {}
);
// ^^^ callback will expect Promise<Record<string, number>> return type;
// initialValue, accumulator and reducedValue will be of type Record<string, number>.

(^ back to index)