UNPKG

1.66 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(object, name, typeName, values = []) {
11 if (!object.hasOwnProperty(name)) {
12 throw Error(`Missing property '${name}'`);
13 }
14 const value = object[name];
15 if (typeName !== void 0) {
16 let valid = true;
17 switch (typeName) {
18 case 'array':
19 valid = Array.isArray(value);
20 break;
21 case 'object':
22 valid = typeof value !== 'undefined';
23 break;
24 default:
25 valid = typeof value === typeName;
26 }
27 if (!valid) {
28 throw new Error(`Property '${name}' is not of type '${typeName}'`);
29 }
30 if (values.length > 0) {
31 let valid = true;
32 switch (typeName) {
33 case 'string':
34 case 'number':
35 case 'boolean':
36 valid = values.includes(value);
37 break;
38 default:
39 valid = values.findIndex(v => v === value) >= 0;
40 break;
41 }
42 if (!valid) {
43 throw new Error(`Property '${name}' is not one of the valid values ${JSON.stringify(values)}`);
44 }
45 }
46 }
47}
48exports.validateProperty = validateProperty;
49//# sourceMappingURL=validate.js.map
\No newline at end of file