Skip to content

Commit

Permalink
.map(value, counter), as per tc39/proposal-iterator-helpers#211
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiancook committed Jul 17, 2023
1 parent 3f97f82 commit e30a2a2
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
6 changes: 4 additions & 2 deletions src/operations/async/map.ts
@@ -1,13 +1,15 @@
import { Arguments, AsyncOperation, Name } from "../operation";

export interface MapFn<T, O> {
(value: T): O | Promise<O>;
(value: T, counter: number): O | Promise<O>;
}

export function map<T, O>(callbackFn: MapFn<T, O>) {
const fn: AsyncOperation<T, AsyncIterable<O>> = async function *map(iterable) {
let counter: number = -1;
for await (const value of async(iterable)) {
yield callbackFn(value);
counter += 1;
yield callbackFn(value, counter);
}
async function *async(value: AsyncIterable<T>) {
yield * value;
Expand Down
6 changes: 4 additions & 2 deletions src/operations/sync/map.ts
Expand Up @@ -2,15 +2,17 @@ import { Arguments, AsyncFn, GetAsync, Name, SyncOperation } from "../operation"
import { isAsyncIterable, isIterable } from "../../async-like";
import * as Async from "../async";

export type MapFn<T, O> = (value: T) => O;
export type MapFn<T, O> = (value: T, counter: number) => O;

export function map<T, O>(callbackFn: MapFn<T, O>) {
const fn: SyncOperation<T, Iterable<O>> = function *map(iterable) {
if (isAsyncIterable(iterable) && !isIterable(iterable)) throw new Async.ExpectedAsyncOperationError(
fn[GetAsync]()
);
let counter = -1;
for (const value of iterable) {
yield callbackFn(value);
counter += 1;
yield callbackFn(value, counter);
}
};
fn[Name] = "map";
Expand Down

0 comments on commit e30a2a2

Please sign in to comment.