Skip to content

Commit

Permalink
Support this argument for Micro.gen
Browse files Browse the repository at this point in the history
  • Loading branch information
maksim.khramtsov authored and tim-smart committed Jun 24, 2024
1 parent 69507a8 commit 6143323
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/early-olives-lay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": minor
---

Support `this` argument for `Micro.gen`
12 changes: 10 additions & 2 deletions packages/effect/src/Micro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1223,14 +1223,22 @@ export const never: Micro<never> = async<never>(function() {
* @experimental
* @category constructors
*/
export const gen = <Eff extends YieldWrap<Micro<any, any, any>>, AEff>(
f: () => Generator<Eff, AEff, never>
export const gen = <Self, Eff extends YieldWrap<Micro<any, any, any>>, AEff>(
...args:
| [self: Self, body: (this: Self) => Generator<Eff, AEff, never>]
| [body: () => Generator<Eff, AEff, never>]
): Micro<
AEff,
[Eff] extends [never] ? never : [Eff] extends [YieldWrap<Micro<infer _A, infer E, infer _R>>] ? E : never,
[Eff] extends [never] ? never : [Eff] extends [YieldWrap<Micro<infer _A, infer _E, infer R>>] ? R : never
> =>
make(function(env, onResult) {
let f: () => Generator<Eff, AEff, never>
if (args.length === 1) {
f = args[0]
} else {
f = args[1].bind(args[0])
}
const iterator = f() as Iterator<YieldWrap<Micro<any, any, any>>, AEff, any>
let running = false
let value: any = undefined
Expand Down
21 changes: 15 additions & 6 deletions packages/effect/test/Micro.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,21 @@ describe.concurrent("Micro", () => {
Micro.runPromise
))

it("gen", () =>
Micro.gen(function*() {
const result = yield* Micro.succeed(1)
assert.strictEqual(result, 1)
return result
}).pipe(Micro.runPromise).then((_) => assert.deepStrictEqual(_, 1)))
describe("gen", () => {
it("gen", () =>
Micro.gen(function*() {
const result = yield* Micro.succeed(1)
assert.strictEqual(result, 1)
return result
}).pipe(Micro.runPromise).then((_) => assert.deepStrictEqual(_, 1)))

it("gen with context", () =>
Micro.gen({ a: 1, b: 2 }, function*() {
const result = yield* Micro.succeed(this.a)
assert.strictEqual(result, 1)
return result + this.b
}).pipe(Micro.runPromise).then((_) => assert.deepStrictEqual(_, 3)))
})

describe("forEach", () => {
it("sequential", () =>
Expand Down

0 comments on commit 6143323

Please sign in to comment.