-
Notifications
You must be signed in to change notification settings - Fork 0
/
recursive.js
48 lines (38 loc) 路 1.03 KB
/
recursive.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// @ts-check
/** @typedef {import('redux').Reducer} Reducer */
/** @typedef {import('mutant-json').MutantOptions} MutantOptions */
const mutateJson = require('mutant-json');
const isPromise = require('@cuser/utils/isPromise');
/**
* Creates a recursive reducer for a certain key by, default parent
* @param {Reducer} reducer
* @param {MutantOptions} opts
*/
const recursiveReducer = (reducer, opts) => {
return (state, action) => {
if (typeof state !== 'object') {
return state;
}
let value = reducer(state, action);
if (value !== undefined) {
return value
}
return mutateJson(state, (mutate, value) => {
if (isPromise(value)) {
return mutate(value.then((value) => {
if (value !== undefined) {
return { value };
}
}));
}
value = reducer(value, action);
if (value !== undefined) {
mutate({ value });
}
}, {
test: '@parent', once: true,
...opts,
});
}
}
module.exports = recursiveReducer;