diff options
author | (quasar) nebula <qznebula@protonmail.com> | 2023-12-30 15:46:44 -0400 |
---|---|---|
committer | (quasar) nebula <qznebula@protonmail.com> | 2023-12-30 15:49:11 -0400 |
commit | 42978bf0b5beebb3a49797d3d800a2c3e4b0c5e9 (patch) | |
tree | 95296405b0fb84c78134f420f36fe6f8898d53dc | |
parent | 7d629c0cb7f5b02289c92d8a6017e5bddfa69df8 (diff) |
validators: embed is() in oneOf()
-rw-r--r-- | src/data/things/validators.js | 31 |
1 files changed, 30 insertions, 1 deletions
diff --git a/src/data/things/validators.js b/src/data/things/validators.js index 6add3655..0cc20229 100644 --- a/src/data/things/validators.js +++ b/src/data/things/validators.js @@ -192,13 +192,17 @@ export function is(...values) { }; } - return (value) => { + const fn = (value) => { if (!values.has(value)) { throw new TypeError(`Expected one of ${Array.from(values).join(' ')}, got ${value}`); } return true; }; + + setValidatorCreatorMeta(fn, is, {values}); + + return fn; } function validateArrayItemsHelper(itemValidator) { @@ -603,6 +607,7 @@ export const isAdditionalNameList = validateArrayItems(isAdditionalName); // Compositional utilities export function oneOf(...validators) { + const validConstants = new Set(); const validConstructors = new Set(); const validTypes = new Set(); @@ -613,6 +618,12 @@ export function oneOf(...validators) { const creatorMeta = getValidatorCreatorMeta(validator); switch (creator) { + case is: + for (const value of creatorMeta.values) { + validConstants.add(value); + } + break; + case validateInstanceOf: validConstructors.add(creatorMeta.constructor); break; @@ -630,6 +641,10 @@ export function oneOf(...validators) { return (value) => { const errorInfo = []; + if (validConstants.has(value)) { + return true; + } + if (!empty(validTypes)) { if (validTypes.has(typeof value)) { return true; @@ -663,6 +678,20 @@ export function oneOf(...validators) { let offset = 0; + if (!empty(validConstants)) { + const constants = + Array.from(validConstants); + + const gotPart = `, got ${value}`; + + prefaceErrorInfo.push([ + null, + offset++, + new TypeError( + `Expected one of ${constants.join(' ')}` + gotPart), + ]); + } + if (!empty(validTypes)) { const types = Array.from(validTypes); |