Skip to content

Commit

Permalink
feat(guard): Add optional message.
Browse files Browse the repository at this point in the history
  • Loading branch information
cartant committed Jul 23, 2017
1 parent e4bf46e commit e714d9a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
17 changes: 17 additions & 0 deletions source/let/guard-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,21 @@ describe("let/guard", () => {
m.expect(destination).toBeObservable(expected);
m.expect(source).toHaveSubscriptions(subs);
}));

it("should support an error messge", marbles((m) => {

const values = { a: 1, b: 2, c: "three" };
const message = "Not a number";

const source = m.cold("-a-b-c-|", values);
const subs = "^----!";
const expected = m.cold("-a-b-#", values, new Error(message));

const destination = source.let(guard(
(value): value is number => typeof value === "number",
message
));
m.expect(destination).toBeObservable(expected);
m.expect(source).toHaveSubscriptions(subs);
}));
});
7 changes: 5 additions & 2 deletions source/let/guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,18 @@ import { Observable } from "rxjs/Observable";

import "rxjs/add/operator/map";

export function guard<T, R extends T>(guard: (value: T) => value is R): (source: Observable<T>) => Observable<R> {
export function guard<T, R extends T>(
guard: (value: T) => value is R,
message?: string
): (source: Observable<T>) => Observable<R> {

return (source: Observable<T>) => source.map((value) => {

if (guard(value)) {
return value as R;
}

const error = new Error("Guard rejection.");
const error = new Error(message || "Guard rejection.");
error["value"] = value;
throw error;
});
Expand Down

0 comments on commit e714d9a

Please sign in to comment.