Skip to content
This repository was archived by the owner on Sep 17, 2023. It is now read-only.

Commit 061d1ab

Browse files
committed
FnContextKey.byDefault constructs default function
1 parent 56d32b0 commit 061d1ab

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed

src/fn-context-key.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1+
import { noop } from 'call-thru';
12
import { AfterEvent, EventKeeper } from 'fun-events';
2-
import { ContextSeedKey, ContextValueOpts } from './context-key';
3+
import { ContextKeyDefault, ContextSeedKey, ContextValueOpts } from './context-key';
34
import { ContextKeyError } from './context-key-error';
45
import { ContextUpKey, ContextUpRef } from './context-up-key';
56
import { ContextValues } from './context-values';
@@ -36,7 +37,8 @@ export class FnContextKey<Args extends any[], Ret = void>
3637
/**
3738
* Constructs a function that will be called unless fallback provided.
3839
*/
39-
readonly byDefault: (this: void, context: ContextValues) => (this: void, ...args: Args) => Ret;
40+
readonly byDefault: (this: void, context: ContextValues, key: FnContextKey<Args, Ret>) =>
41+
(this: void, ...args: Args) => Ret;
4042

4143
/**
4244
* Constructs updatable context function key.
@@ -50,16 +52,16 @@ export class FnContextKey<Args extends any[], Ret = void>
5052
name: string,
5153
{
5254
seedKey,
53-
byDefault = () => () => { throw new ContextKeyError(this); },
55+
byDefault = noop,
5456
}: {
5557
seedKey?: ContextSeedKey<
5658
((this: void, ...args: Args) => Ret) | EventKeeper<((this: void, ...args: Args) => Ret)[]>,
5759
AfterEvent<((this: void, ...args: Args) => Ret)[]>>,
58-
byDefault?: (this: void, context: ContextValues) => (this: void, ...args: Args) => Ret,
60+
byDefault?: ContextKeyDefault<(this: void, ...args: Args) => Ret, FnContextKey<Args, Ret>>,
5961
} = {},
6062
) {
6163
super(name, seedKey);
62-
this.byDefault = byDefault;
64+
this.byDefault = (context, key) => byDefault(context, key) || (() => { throw new ContextKeyError(this); });
6365
}
6466

6567
grow<Ctx extends ContextValues>(
@@ -77,9 +79,10 @@ export class FnContextKey<Args extends any[], Ret = void>
7779
delegated = fns[fns.length - 1];
7880
} else {
7981

80-
const fallback = opts.byDefault(() => this.byDefault(opts.context));
82+
const defaultProvider = () => this.byDefault(opts.context, this);
83+
const fallback = opts.byDefault(defaultProvider);
8184

82-
delegated = fallback || this.byDefault(opts.context);
85+
delegated = fallback || defaultProvider();
8386
}
8487
});
8588

0 commit comments

Comments
 (0)