Sykander / iterable-async

Iterable Async Methods
https://www.npmjs.com/package/iterable-async
MIT License
5 stars 0 forks source link

TypeScript type declaration file #73

Closed geopic closed 4 years ago

geopic commented 4 years ago

Hello. I saw from Reddit that this package is lacking a type declaration file for TS developers, would you like me to write one up?

Sykander commented 4 years ago

Hi,

Yes that'd be great thanks!

Looking forward to your contribution! 😄

Sykander commented 4 years ago

Here are the list of items which are exported from the module.

Feel free to add typescript as a dev dependency to test that whichever type defintion you add is still correct.

geopic commented 4 years ago

Cheers Sykander, I'll start on it in the next day or so. :smile:

geopic commented 4 years ago

A question, how would developers use this package? Would they set a variable to the AsyncArray class and then fill that with data, or would they use individual methods like asyncFilter, asyncSort etc on a regular array?

Sykander commented 4 years ago

Hi George,

So the module can be used either way as suggested in your comment.

First way:

const arr = [2, 4, 3, 6, 2, 2, 5, 6, , , ];
// AsyncArray inherits from Array so it has access to static methods like 'from' or 'isArray'
const asyncArr = AsyncArray.from(arr);

const sorted = await asyncArr.asyncSort();
const asyncArr = new AsyncArray();
asyncArr.push(...[2, 4, 3, 6, 2, 2, 5, 6, , , ]);

const sorted = await asyncArr.asyncSort();

Of if you would prefer to add the method to your own collection

const arr = [2, 4, 3, 6, 2, 2, 5, 6, , , ];
arr.asyncSort = asyncSort;

const sorted = await arr.asyncSort();

You can find a working code pend here: https://npm.runkit.com/iterable-async

It's pretty nifty if you just want to mess around with the package.

Note:

This module was mostly just created for the asyncMap method which allows you to easily map over a list of objects (eg. models to save to a db which will be async mapped by saving), and then convert them all into one large promise to await all at once.

The other methods came as an extension on this core functionality.

Example:

const {
    AsyncArray,
    asyncFind,
    asyncFindIndex,
    asyncFilter,
    asyncForEach,
    asyncMap,
    asyncSort
} = require('iterable-async');

const arr = [2, 4, 3, 6, 2, 2, 5, 6];
const asyncArr = AsyncArray.from(arr);

await asyncArr.asyncSort(async (a, b) => {
    return new Promise(resolve => {
        setTimeout(() => resolve(a - b), 20)
    });
});

Here, I've written a quick example of a sort which uses async comparisons (eg. some call to some api) which you can paste into a code pen and run. 👍

geopic commented 4 years ago

Thanks for the example. I've finished writing up the types declaration file and will submit a pull request.