Skip to content

Commit

Permalink
refs #12 add Future.lift but for now with the pre-TS3.0 api which sup…
Browse files Browse the repository at this point in the history
…ports only up to 5 parameters.
  • Loading branch information
emmanueltouzery committed Sep 3, 2018
1 parent 8bbc983 commit 20e14b1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Future.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,22 @@ export class Future<T> {
return (p1,p2) => p1.flatMap(a1 => p2.map(a2 => fn(a1,a2)));
}

/**
* Take a function returning a Promise
* and lift it to return a [[Future]] instead.
*/
static lift<U>(fn:()=>Promise<U>): ()=>Future<U>
static lift<T1,U>(fn:(x:T1)=>Promise<U>): (x:T1)=>Future<U>
static lift<T1,T2,U>(fn:(x:T1,y:T2)=>Promise<U>): (x:T1,y:T2)=>Future<U>
static lift<T1,T2,T3,U>(fn:(x:T1,y:T2,z:T3)=>Promise<U>): (x:T1,y:T2,z:T3)=>Future<U>
static lift<T1,T2,T3,T4,U>(fn:(x:T1,y:T2,z:T3,z1:T4)=>Promise<U>): (x:T1,y:T2,z:T3,z1:T4)=>Future<U>
static lift<T1,T2,T3,T4,T5,U>(fn:(x:T1,y:T2,z:T3,z1:T4,z2:T5)=>Promise<U>): (x:T1,y:T2,z:T3,z1:T4,z2:T5)=>Future<U>
static lift<L,U>(fn:any): any {
return (...args:any[]) => {
return Future.of(fn(...args));
};
}

/**
* Transform the value contained in a successful Future. Has no effect
* if the Future was failed. Will turn a successful Future in a failed
Expand Down
18 changes: 18 additions & 0 deletions tests/Future.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,24 @@ describe("Future.liftA*", () => {
return ensureFailedWithValue("sorry", computationPromise.toPromise());
});
});
describe("Future.lift", () => {
it("lifts a simple promise", async () => {
const fn = (x:number) => Promise.resolve(x+1);
const fn2 = Future.lift(fn);
assert.equal(5, await fn2(4));
});
it("lifts a failing promise", async () => {
const fn = (x:number) => Promise.reject(x+1);
const fn2 = Future.lift(fn);
try {
await fn2(4);
assert.ok(false);
} catch (ex) {
assert.equal(5, ex);
}

});
});
describe("Future.traverse", () => {
it("traverses properly", async () => {
assert.deepEqual([1,2,3], await Future.traverse([1,2,3], Future.ok).map(v => v.toArray()));
Expand Down

0 comments on commit 20e14b1

Please sign in to comment.