You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

functional.ts 705 B

12345678910111213141516171819202122
  1. /*
  2. * @Author: 赵伟
  3. * @Date: 2024-10-12 14:27:29
  4. * @Description: 函数式编程
  5. */
  6. /**
  7. * 安全调用函数,如果参数是 `undefined` 或 `null`,直接返回 `undefined` 或 `null`,而不会导致异常
  8. *
  9. * @param fn - 要调用的函数
  10. * @returns 封装后的函数,该函数的参数如果是 `undefined` 或 `null`,结果直接返回 `undefined` 或 `null`,而不会导致异常
  11. */
  12. export function safeInvoke<T, M>(
  13. fn: (value: T) => M | undefined | null,
  14. ): (value: T | undefined | null) => M | undefined | null {
  15. return (arg: T | undefined | null) => {
  16. if (arg === undefined || arg === null) {
  17. return arg as undefined | null;
  18. }
  19. return fn(arg);
  20. };
  21. }