From 052861b7c4866cab23a69820c2f4712f77151fb0 Mon Sep 17 00:00:00 2001 From: Anton Golub Date: Mon, 13 Jun 2022 17:00:09 +0300 Subject: [PATCH] feat: provide configurable ref for `ctx()` --- README.md | 5 +++++ src/experimental.ts | 4 ++-- test/experimental.test.js | 8 ++++++++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e686e05bc4..9b634d1c53 100644 --- a/README.md +++ b/README.md @@ -502,6 +502,11 @@ ctx(async ($) => { // _$.cwd refers to /foo // but _$.cwd !== $.cwd }) + +const ref = $.bind(null) +ctx(($) => { + ref === $ // true +}, ref) ``` ### `log()` diff --git a/src/experimental.ts b/src/experimental.ts index 70138a4f53..ccf15d5060 100644 --- a/src/experimental.ts +++ b/src/experimental.ts @@ -81,8 +81,8 @@ export function startSpinner(title = '') { )(setInterval(spin, 100)) } -export function ctx(cb: (_$: Zx) => R): R { - const _$ = Object.assign($.bind(null), getCtx()) +export function ctx(cb: (_$: Zx) => R, ref: Zx = $.bind(null)): R { + const _$ = Object.assign(ref, getCtx()) return runInCtx(_$, cb, _$) } diff --git a/test/experimental.test.js b/test/experimental.test.js index 0336945f69..908e1ff2cb 100644 --- a/test/experimental.test.js +++ b/test/experimental.test.js @@ -111,6 +111,14 @@ test('ctx() provides isolates running scopes', async () => { $.verbose = false }) +test('ctx accepts optional ref', () => { + const ref = $.bind(null) + + ctx(($) => { + assert.is(ref, $) + }, ref) +}) + test('bound ctx is attached to Promise', async () => { const kResourceStoreSymbol = Object.getOwnPropertySymbols( new Promise(() => {})