-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c7a4f3b
commit 3b2e403
Showing
4 changed files
with
59 additions
and
179 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
// Copyright (c) Jupyter Development Team. | ||
// Distributed under the terms of the Modified BSD License. | ||
|
||
/** | ||
* Validate a property as being on an object, and optionally | ||
* of a given type and among a given set of values. | ||
*/ | ||
export function validateProperty( | ||
object: any, | ||
name: string, | ||
typeName?: string, | ||
values: any[] = [] | ||
): void { | ||
if (!object.hasOwnProperty(name)) { | ||
throw Error(`Missing property '${name}'`); | ||
} | ||
const value = object[name]; | ||
|
||
if (typeName !== void 0) { | ||
let valid = true; | ||
switch (typeName) { | ||
case 'array': | ||
valid = Array.isArray(value); | ||
break; | ||
case 'object': | ||
valid = typeof value !== 'undefined'; | ||
break; | ||
default: | ||
valid = typeof value === typeName; | ||
} | ||
if (!valid) { | ||
throw new Error(`Property '${name}' is not of type '${typeName}`); | ||
} | ||
|
||
if (values.length > 0) { | ||
let valid = true; | ||
switch (typeName) { | ||
case 'string': | ||
case 'number': | ||
case 'boolean': | ||
valid = values.includes(value); | ||
break; | ||
default: | ||
valid = values.findIndex(v => v === value) >= 0; | ||
break; | ||
} | ||
if (!valid) { | ||
throw new Error( | ||
`Property '${name}' is not one of the valid values ${JSON.stringify( | ||
values | ||
)}` | ||
); | ||
} | ||
} | ||
} | ||
} |