Skip to content

Commit 2d0e5ca

Browse files
committed
feat: dependencies can be a function
1 parent 34f8676 commit 2d0e5ca

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

src/index.ts

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -140,14 +140,17 @@ export interface Plugin<
140140
state: T[Options.State]
141141
) => {}
142142
[Options.Keys]?: Array<string | number | symbol>
143-
[Options.Dependencies]?: U[]
143+
[Options.Dependencies]?:
144+
| U[]
145+
| ((log: Action<U>[], state: T[Options.State]) => U[])
144146
[Options.Enabled]?: (log: Action<U>[], state: T[Options.State]) => boolean
145147
[Options.Conflicts]?: U[]
146148
[Options.InitialState]?: Partial<T[Options.State]>
147149
[Options.Reducer]?: (log: Action<U>[]) => Partial<T[Options.State]>
148150
}
149151

150152
import {
153+
isArray,
151154
isBoolean,
152155
isFunction,
153156
isNumber,
@@ -234,7 +237,16 @@ const normalizeRecords = <T extends Settings>(
234237
)
235238
}
236239

237-
if (!every(record[Options.Dependencies], isType)) {
240+
if (
241+
!(
242+
isFunction(record[Options.Dependencies]) ||
243+
(isArray(record[Options.Dependencies]) &&
244+
every(
245+
record[Options.Dependencies] as Array<number | string | symbol>,
246+
isType
247+
))
248+
)
249+
) {
238250
throw new Error(
239251
`Not valid [Options.Dependencies] in the ${String(
240252
record[Options.Type]
@@ -321,8 +333,14 @@ class Lens<T extends Settings> {
321333
record: Required<Plugin<Types<T>, T>>
322334
): Array<() => boolean> => [
323335
() =>
324-
every(record[Options.Dependencies], type =>
325-
some(this.state.log, action => action.type === type)
336+
every(
337+
isFunction(record[Options.Dependencies])
338+
? (record[Options.Dependencies] as Function)(
339+
this.state.log,
340+
this.state.state
341+
)
342+
: record[Options.Dependencies],
343+
type => some(this.state.log, action => action.type === type)
326344
),
327345
() => record[Options.Enabled](this.state.log, this.state.state),
328346
() =>

test/email/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ export const email = builder<Settings>([
5858
[Options.Type]: SYMBOL_BODY,
5959
[Options.Once]: true,
6060
[Options.Keys]: ['body'],
61-
[Options.Dependencies]: [SYMBOL_TO, SYMBOL_SUBJECT],
61+
[Options.Dependencies]: () => [SYMBOL_TO, SYMBOL_SUBJECT],
6262
[Options.Reducer]: log => ({
6363
body: get(find(log, action => action.type === SYMBOL_BODY), 'payload')
6464
}),

0 commit comments

Comments
 (0)