Browse Source

Only infer label when predicate fails - fixes #115

iss115
Sam Verschueren 6 years ago
parent
commit
e277d00218
  1. 11
      source/index.ts
  2. 24
      source/lib/predicates/predicate.ts

11
source/index.ts

@ -201,12 +201,15 @@ export interface Ow {
any(...predicate: BasePredicate[]): AnyPredicate;
}
const main = <T>(value: T, labelOrPredicate: BasePredicate<T> | string | undefined, predicate?: BasePredicate<T>) => {
const main = <T>(value: T, labelOrPredicate: BasePredicate<T> | string | Function | undefined, predicate?: BasePredicate<T>) => {
let label: any = labelOrPredicate;
let testPredicate: any = predicate;
if (isPredicate(labelOrPredicate)) {
label = inferLabel(callsites());
const stackFrames = callsites();
// Pass in a label function to only infer it when it fails
label = () => inferLabel(stackFrames);
testPredicate = labelOrPredicate;
}
@ -227,7 +230,9 @@ Object.defineProperties(main, {
create: {
value: <T>(labelOrPredicate: BasePredicate<T> | string | undefined, predicate?: BasePredicate<T>) => (value: T) => {
if (isPredicate(labelOrPredicate)) {
return main(value, inferLabel(callsites()), labelOrPredicate);
const stackFrames = callsites();
return main(value, () => inferLabel(stackFrames), labelOrPredicate);
}
return main(value, labelOrPredicate, predicate);

24
source/lib/predicates/predicate.ts

@ -55,18 +55,26 @@ export class Predicate<T = any> implements BasePredicate<T> {
* @hidden
*/
// tslint:disable completed-docs
[testSymbol](value: T, main: Ow, label?: string) {
const label2 = label
? `${this.type} \`${label}\``
: this.type;
[testSymbol](value: T, main: Ow, label?: string | Function) {
for (const {validator, message} of this.context.validators) {
const result = validator(value);
if (typeof result !== 'boolean' || !result) {
// TODO: Modify the stack output to show the original `ow()` call instead of this `throw` statement
throw new ArgumentError(message(value, label2, result), main);
if (result === true) {
continue;
}
let label2 = label;
if (typeof label === 'function') {
label2 = label();
}
label2 = label2
? `${this.type} \`${label2}\``
: this.type;
// TODO: Modify the stack output to show the original `ow()` call instead of this `throw` statement
throw new ArgumentError(message(value, label2, result), main);
}
}

Loading…
Cancel
Save