diff --git a/src/optional.ts b/src/optional.ts index 7ad1628..c71997f 100644 --- a/src/optional.ts +++ b/src/optional.ts @@ -12,6 +12,11 @@ class Optional { 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(optionals: Optional[]): T[] { return optionals.reduce((acc, elem) => { elem.forEach((value: T) => { diff --git a/src/try.ts b/src/try.ts index 4215aa8..1d7af04 100644 --- a/src/try.ts +++ b/src/try.ts @@ -7,6 +7,20 @@ class Try { private _err: Error; private _value: T; + /** + * Attempts to flatten an array of tries + * @param tries The list of tries to flatten + * @returns {Try} + */ + static all(tries: Try[]): Try { + return Try.attempt(() => { + 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 diff --git a/test/try_spec.ts b/test/try_spec.ts index a3f78be..29b5cfd 100644 --- a/test/try_spec.ts +++ b/test/try_spec.ts @@ -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);