File tree 1 file changed +23
-4
lines changed
1 file changed +23
-4
lines changed Original file line number Diff line number Diff line change @@ -425,12 +425,31 @@ export const flatten = (arr: any[]) => arr.reduce(flattenR, []);
425
425
* oneString.filter(assertPredicate(isNumber, "Not all numbers")); // throws Error(""Not all numbers"");
426
426
* ```
427
427
*/
428
- export function assertPredicate < T > ( predicate : Predicate < T > , errMsg : ( string | Function ) = "assert failure" ) : Predicate < T > {
429
- return ( obj : T ) => {
430
- if ( ! predicate ( obj ) ) {
428
+ export const assertPredicate : < T > ( predicate : Predicate < T > , errMsg : ( string | Function ) ) => Predicate < T > = assertFn ;
429
+ /**
430
+ * Given a .map function, builds a .map function which throws an error if any mapped elements do not pass a truthyness test.
431
+ * @example
432
+ * ```
433
+ *
434
+ * var data = { foo: 1, bar: 2 };
435
+ *
436
+ * let keys = [ 'foo', 'bar' ]
437
+ * let values = keys.map(assertMap(key => data[key], "Key not found"));
438
+ * // values is [1, 2]
439
+ *
440
+ * let keys = [ 'foo', 'bar', 'baz' ]
441
+ * let values = keys.map(assertMap(key => data[key], "Key not found"));
442
+ * // throws Error("Key not found")
443
+ * ```
444
+ */
445
+ export const assertMap : < T , U > ( mapFn : ( t : T ) => U , errMsg : ( string | Function ) ) => ( t : T ) => U = assertFn ;
446
+ export function assertFn ( predicateOrMap : Function , errMsg : ( string | Function ) = "assert failure" ) : any {
447
+ return ( obj ) => {
448
+ let result = predicateOrMap ( obj ) ;
449
+ if ( ! result ) {
431
450
throw new Error ( isFunction ( errMsg ) ? ( < Function > errMsg ) ( obj ) : errMsg ) ;
432
451
}
433
- return true ;
452
+ return result ;
434
453
} ;
435
454
}
436
455
You can’t perform that action at this time.
0 commit comments