UNPKG

1.74 kBJavaScriptView Raw
1"use strict";
2// Copyright (c) Jupyter Development Team.
3// Distributed under the terms of the Modified BSD License.
4Object.defineProperty(exports, "__esModule", { value: true });
5exports.validateProperty = void 0;
6/**
7 * Validate a property as being on an object, and optionally
8 * of a given type and among a given set of values.
9 */
10function validateProperty(
11// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
12object, name, typeName, values = []) {
13 if (!object.hasOwnProperty(name)) {
14 throw Error(`Missing property '${name}'`);
15 }
16 const value = object[name];
17 if (typeName !== void 0) {
18 let valid = true;
19 switch (typeName) {
20 case 'array':
21 valid = Array.isArray(value);
22 break;
23 case 'object':
24 valid = typeof value !== 'undefined';
25 break;
26 default:
27 valid = typeof value === typeName;
28 }
29 if (!valid) {
30 throw new Error(`Property '${name}' is not of type '${typeName}'`);
31 }
32 if (values.length > 0) {
33 let valid = true;
34 switch (typeName) {
35 case 'string':
36 case 'number':
37 case 'boolean':
38 valid = values.includes(value);
39 break;
40 default:
41 valid = values.findIndex(v => v === value) >= 0;
42 break;
43 }
44 if (!valid) {
45 throw new Error(`Property '${name}' is not one of the valid values ${JSON.stringify(values)}`);
46 }
47 }
48 }
49}
50exports.validateProperty = validateProperty;
51//# sourceMappingURL=validate.js.map
\No newline at end of file