Skip to content

Commit f044f53

Browse files
feat(assertMap): Add a [].map() helper that asserts that each element is truthy
1 parent 8eee242 commit f044f53

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

src/common/common.ts

+23-4
Original file line numberDiff line numberDiff line change
@@ -425,12 +425,31 @@ export const flatten = (arr: any[]) => arr.reduce(flattenR, []);
425425
* oneString.filter(assertPredicate(isNumber, "Not all numbers")); // throws Error(""Not all numbers"");
426426
* ```
427427
*/
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) {
431450
throw new Error(isFunction(errMsg) ? (<Function> errMsg)(obj) : errMsg);
432451
}
433-
return true;
452+
return result;
434453
};
435454
}
436455

0 commit comments

Comments
 (0)