UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

31 lines (30 loc) 1.12 kB
import { isArray } from "../util/array.js"; import { isProp } from "../util/object.js"; import { Schema } from "./Schema.js"; /** Get a `ChoiceOptions` object for a set of `PossibleChoiceOptions`. */ function _getChoiceOptions(options) { return isArray(options) ? Object.fromEntries(options.map(_getChoiceOption)) : options; } function _getChoiceOption(k) { return [k, k]; } /** Choose from an allowed set of values. */ export class ChoiceSchema extends Schema { options; constructor({ one = "choice", title = "Choice", placeholder = `No ${one}`, options, value, ...rest }) { super({ one, title, value, placeholder, ...rest }); this.options = _getChoiceOptions(options); } validate(unsafeValue = this.value) { if (typeof unsafeValue === "string" && isProp(this.options, unsafeValue)) return unsafeValue; throw unsafeValue ? `Unknown ${this.one}` : "Required"; } format(value) { return this.options[value]; } } /** Choose from an allowed set of values. */ export function CHOICE(options) { return new ChoiceSchema({ options }); }