Skip to content

Commit

Permalink
feat: add index param to callback of .map and .forEach
Browse files Browse the repository at this point in the history
  • Loading branch information
RebeccaStevens committed Dec 5, 2021
1 parent 3a70457 commit 74295f8
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
7 changes: 4 additions & 3 deletions src/iterate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class IteratorWithOperators<T> implements IterableIterator<T> {
/**
* Returns a new Iterator by running each element thru iteratee
*/
map<R>(iteratee: (value: T) => R): IteratorWithOperators<R> {
map<R>(iteratee: (value: T, index: number) => R): IteratorWithOperators<R> {
return new IteratorWithOperators(new MapIterator(this.source, iteratee))
}

Expand Down Expand Up @@ -192,14 +192,15 @@ export class IteratorWithOperators<T> implements IterableIterator<T> {
/**
* Iterates and invokes `iteratee` for every element emitted by the Iterator
*/
forEach(iteratee: (value: T) => any): void {
forEach(iteratee: (value: T, index: number) => any): void {
let result: IteratorResult<T>
let index = 0;
while (true) {
result = this.source.next()
if (result.done) {
break
}
iteratee(result.value)
iteratee(result.value, index++)
}
}

Expand Down
8 changes: 6 additions & 2 deletions src/map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@
* An iterator that emits results by running each element through a provided predicate
*/
export class MapIterator<T, R> implements Iterator<R> {
constructor(private source: Iterator<T>, private iteratee: (value: T) => R) {}
private index: number

constructor(private source: Iterator<T>, private iteratee: (value: T, index: number) => R) {
this.index = 0
}

next(): IteratorResult<R> {
const { value, done } = this.source.next()
return { value: !done && this.iteratee(value), done } as IteratorResult<R>
return { value: !done && this.iteratee(value, this.index++), done } as IteratorResult<R>
}
}

0 comments on commit 74295f8

Please sign in to comment.