forked from typescript-eslint/typescript-eslint
/
applyDefault.ts
40 lines (33 loc) · 1.04 KB
/
applyDefault.ts
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
import { deepMerge, isObjectNotArray } from './deepMerge';
/**
* Pure function - doesn't mutate either parameter!
* Uses the default options and overrides with the options provided by the user
* @param defaultOptions the defaults
* @param userOptions the user opts
* @returns the options with defaults
*/
function applyDefault<TUser extends readonly unknown[], TDefault extends TUser>(
defaultOptions: TDefault,
userOptions: TUser | null,
): TDefault {
// clone defaults
const options: AsMutable<TDefault> = JSON.parse(
JSON.stringify(defaultOptions),
);
if (userOptions === null || userOptions === undefined) {
return options;
}
options.forEach((opt, i) => {
if (userOptions[i] !== undefined) {
const userOpt = userOptions[i];
if (isObjectNotArray(userOpt) && isObjectNotArray(opt)) {
options[i] = deepMerge(opt, userOpt);
} else {
options[i] = userOpt;
}
}
});
return options;
}
type AsMutable<T extends {}> = { -readonly [TKey in keyof T]: T[TKey] };
export { applyDefault };