Skip to content

Commit

Permalink
feat(index): Add indexElements.
Browse files Browse the repository at this point in the history
  • Loading branch information
cartant committed Jul 15, 2018
1 parent 7294bd6 commit 435cd47
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions source/operators/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export * from "./debounceTimeSubsequent";
export * from "./defaultObservableIfEmpty";
export * from "./endWith";
export * from "./guard";
export * from "./indexElements";
export * from "./inexorably";
export * from "./initial";
export * from "./instanceOf";
Expand Down
33 changes: 33 additions & 0 deletions source/operators/indexElements-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* @license Use of this source code is governed by an MIT-style license that
* can be found in the LICENSE file at https://github.com/cartant/rxjs-etc
*/
/*tslint:disable:no-unused-expression*/

import { marbles } from "rxjs-marbles";
import { indexElements } from "./indexElements";

describe("indexElements", () => {

it("should index without a project function", marbles(m => {

const source = m.cold("ab-cd-");
const sourceSubs = "^-----";
const expected = m.cold("ab-cd-", { a: 0, b: 1, c: 2, d: 3 });

const destination = source.pipe(indexElements());
m.expect(destination).toBeObservable(expected);
m.expect(source).toHaveSubscriptions(sourceSubs);
}));

it("should index with a project function", marbles(m => {

const source = m.cold("ab-cd-");
const sourceSubs = "^-----";
const expected = m.cold("ab-cd-", { a: "a:0", b: "b:1", c: "c:2", d: "d:3" });

const destination = source.pipe(indexElements((value, index) => `${value}:${index}`));
m.expect(destination).toBeObservable(expected);
m.expect(source).toHaveSubscriptions(sourceSubs);
}));
});
13 changes: 13 additions & 0 deletions source/operators/indexElements.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* @license Use of this source code is governed by an MIT-style license that
* can be found in the LICENSE file at https://github.com/cartant/rxjs-etc
*/

import { OperatorFunction } from "rxjs";
import { map } from "rxjs/operators";

export function indexElements<T>(): OperatorFunction<T, number>;
export function indexElements<T, R>(project: (value: T, index: number) => R): OperatorFunction<T, R>;
export function indexElements<T>(project: (value: T, index: number) => any = (value, index) => index): OperatorFunction<T, any> {
return map<T, any>(project);
}

0 comments on commit 435cd47

Please sign in to comment.