Async versions of array functions with predicate callbacks e.g.
import { findIndex } from 'arrays-sugar'
const array = [1, 2, 3];
findIndex(array, async (number) => number === 2) // 1 ✅
array.findIndex(async (number) => number === 2) // 0 ❌
Built with Typescript for Node.js or the Browser.
A set of purely functional array methods with async predicates: every
, filter
, find
, findIndex
, some
These are used internally in the related AI Sugar package/library. Check it out especially if you're building or working with AI in Typescript/Node.js.
So each function has 2/3 versions:
- default version which is concurrent (uses
Promise.allSettled
internally) and is also available with the suffixConcurrent
// both are equivalent
[1, 2, 3].every(async (number) => number === 2) === true
[1, 2, 3].everyConcurrent(async (number) => number === 2) === true
- optimized version that may not iterate the entire array on condition that the predicate
throws
forfalsy
values (instead of returningfalse
). This is available for all exceptfilter
which has to go through the whole array. Uses the suffixOptimized
.
const result = await findOptimized(array, async (item) => {
if (item <= 1) {
throw new Error("error");
}
return true;
});
- serial version that iterates one at a time (slow). Uses the suffix
Serial
.
const result = await findIndexSerial(array, async (item) => {
await sleep(100);
return item > 1;
});
Using callbacks with promises or async/await inside findIndex always returns truthy for all items in the array.
If you try this in the console or node.js it will always return false
[1, 2, 3].findIndex(async (number) => number === 2) === 1
The same goes for every
, find
, filter
, some
Outside map
it seems only reduce
can work with promise
or async
/await
callbacks
const sum = await [1, 2, 3].reduce((accumulator, number) => {
return accumulator.then(value => value + number)
}, Promise.resolve(0));
console.log(sum) // 6
Async versions of:
indexOf
lastIndexOf
findLast
findLastIndex
Thanks for reading. I welcome your input, suggestions, feedback. Here is the medium article I wrote introducing this library.
Check out the following related libraries that I also built with this release.
ai-sugar AI Sugar is a collection of utility functions for working with AI apis.
const sorted = await ai.sort({
array: ["green", "red", "blue", "yellow"],
prompt: "rainbow color order",
});
// ["red", "yellow", "green", "blue"]
zod-sugar Zod Sugar is basically reverse zod i.e. creates a zod schema from a javascript value:
const object = { foo: "bar", baz: 1 };
const schema = createZod(object);
// z.object({ foo: z.string(), bar: z.number() });
schema.safeParse(object).success // true
Find the best alternatives with one click. Discover similar websites, tools and services instantly while browsing. Never miss out on better options again. Check out Similarly