Skip to content
This repository has been archived by the owner on Jan 16, 2024. It is now read-only.

Commit

Permalink
Merge pull request #13 from Asana/all
Browse files Browse the repository at this point in the history
Adding Try.all
  • Loading branch information
pspeter3 committed Jan 22, 2015
2 parents 4826df9 + 297b89d commit 1177347
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/optional.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ class Optional<T> {
return typeof value === "undefined" || value === null;
}

/**
* Flattens an array of optionals by filtering out the empty optionals
* @param optionals The list of optionals to flatten
* @returns {T{]}
*/
public static flatten<T>(optionals: Optional<T>[]): T[] {
return optionals.reduce((acc, elem) => {
elem.forEach((value: T) => {
Expand Down
14 changes: 14 additions & 0 deletions src/try.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,20 @@ class Try<T> {
private _err: Error;
private _value: T;

/**
* Attempts to flatten an array of tries
* @param tries The list of tries to flatten
* @returns {Try<T[]>}
*/
static all<T>(tries: Try<T>[]): Try<T[]> {
return Try.attempt<T[]>(() => {
return tries.reduce((acc, elem) => {
acc.push(elem.getOrThrow());
return acc;
}, []);
});
}

/**
* Attemps a function and returns a Try for its success
* @param fn The function to attempt
Expand Down
14 changes: 14 additions & 0 deletions test/try_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,20 @@ describe("Try", () => {
};
var ERR = new Error();

describe("#all", () => {
it("should return all of the values if there is not an exception", () => {
var t = tsutil.Try.success(VALUE);
var k = tsutil.Try.success(OTHER);
assert.deepEqual(tsutil.Try.all([t, k]).getOrThrow(), [VALUE, OTHER]);
});

it("should throw if there is an exception", () => {
var t = tsutil.Try.success(VALUE);
var k = tsutil.Try.failure(ERR);
assert.isTrue(tsutil.Try.all([t, k]).isFailure());
});
});

describe("#attempt", () => {
it("should return a value if successful", () => {
var t = tsutil.Try.attempt(VALUE_ACCESSOR);
Expand Down

0 comments on commit 1177347

Please sign in to comment.