CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/util/fill/fill.ts
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import { Assign } from "utility-types";
7
import { Restrict, Optionals } from "./types";
8
9
/**
10
* Given an object: T with some optional parameters
11
* and defaults: a subset of optional parameters from T.
12
*
13
* Explicitly setting a default to `undefined` is not recommended
14
*
15
* @return T except provided defaults are guaranteed
16
*
17
* @example
18
* props: {foo: string; bar?: string},
19
* defaults: {bar: "good stuff"}
20
* => {foo: string; bar: string} // <- Note bar is defined
21
*
22
*
23
* props: {foo: string; bar?: string; baz?: number},
24
* defaults: {bar: "good stuff"}
25
* => {foo: string; bar: string; baz?: number} // <- Note baz is optional
26
* .
27
**/
28
export function fill<T extends object, U extends Optionals<T>>(
29
props: T,
30
defaults: Restrict<U, Optionals<T>, "Defaults cannot contain required values">
31
): Assign<T, U> {
32
const ret: U = {} as any;
33
for (const key in defaults) {
34
if (!props.hasOwnProperty(key) || props[key] == undefined) {
35
ret[key] = defaults[key];
36
}
37
}
38
return Object.assign({}, props, ret);
39
}
40
41