Skip to content

Commit

Permalink
Add index to async map callback (#116)
Browse files Browse the repository at this point in the history
* add index to async map callback
  • Loading branch information
sodiray authored Oct 26, 2022
1 parent 4803110 commit e96ba44
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 15 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "radash",
"version": "8.0.3",
"version": "8.1.0",
"description": "Functional utility library - modern, simple, typed, powerful",
"main": "dist/cjs/index.cjs",
"module": "dist/esm/index.mjs",
Expand Down
10 changes: 7 additions & 3 deletions src/async.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@ export const reduce = async <T, K>(
*/
export const map = async <T, K>(
array: readonly T[],
asyncMapFunc: (item: T) => Promise<K>
asyncMapFunc: (item: T, index: number) => Promise<K>
): Promise<K[]> => {
if (!array) return []
let result = []
let index = 0
for (const value of array) {
const newValue = await asyncMapFunc(value)
const newValue = await asyncMapFunc(value, index++)
result.push(newValue)
}
return result
Expand Down Expand Up @@ -186,7 +188,9 @@ export const tryit = <TFunction extends (...args: any) => any>(
) => {
return async (
...args: ArgumentsType<TFunction>
): Promise<[Error, null] | [null, UnwrapPromisify<ReturnType<TFunction>>]> => {
): Promise<
[Error, null] | [null, UnwrapPromisify<ReturnType<TFunction>>]
> => {
try {
return [null, await func(...(args as any))]
} catch (err) {
Expand Down
23 changes: 12 additions & 11 deletions src/tests/async.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,18 @@ describe("async module", () => {
const result = await _.map<number, number>(numbers, asyncSquare);
assert.deepEqual(result, [1, 4, 9, 16]);
});

test("handles null input", async () => {
const result = await _.map(null, async () => '');
assert.deepEqual(result, []);
});

test("passes correct indexes", async () => {
const array = ['a', 'b', 'c', 'd'];
const mapper = async (l: string, index: number) => `${l}${index}`;
const result = await _.map(array, mapper);
assert.deepEqual(result, ['a0', 'b1', 'c2', 'd3']);
});
});

describe("reduce/asyncReduceV2 function", () => {
Expand Down Expand Up @@ -66,17 +78,6 @@ describe("async module", () => {
});
});

describe("map/asyncMapV2 function", () => {
test("calls asyncMap", async () => {
const numbers = [1, 2, 3, 4];
const asyncSquare = async (a: number): Promise<number> => {
return new Promise((res) => res(a * a));
};
const result = await _.map<number, number>(numbers, asyncSquare);
assert.deepEqual(result, [1, 4, 9, 16]);
});
});

describe("defer function", () => {
test("calls registered defer function", async () => {
let val = 0;
Expand Down

0 comments on commit e96ba44

Please sign in to comment.