From 46b05aa81d294d0df0602c10f7e293ab44534c24 Mon Sep 17 00:00:00 2001 From: Tsu-ba-me Date: Fri, 22 Jul 2022 20:39:23 -0400 Subject: [PATCH] fix(striker-ui): add function to simplify (not) empty checks --- striker-ui/lib/isEmpty.ts | 26 ++++++++++++++++++++++++++ striker-ui/types/MapToType.d.ts | 4 ++++ 2 files changed, 30 insertions(+) create mode 100644 striker-ui/lib/isEmpty.ts create mode 100644 striker-ui/types/MapToType.d.ts diff --git a/striker-ui/lib/isEmpty.ts b/striker-ui/lib/isEmpty.ts new file mode 100644 index 00000000..248ac067 --- /dev/null +++ b/striker-ui/lib/isEmpty.ts @@ -0,0 +1,26 @@ +type MapToValueIsEmptyFunction = { + [TypeName in keyof MapToType]: (value: MapToType[TypeName]) => boolean; +}; + +const MAP_TO_VALUE_IS_EMPTY_FUNCTION: MapToValueIsEmptyFunction = { + number: (value: number) => value === 0, + string: (value: string) => value.trim().length === 0, +}; + +const isEmpty = ( + values: Array, + { not, fn = 'every' }: { not?: boolean; fn?: 'every' | 'some' } = {}, +): boolean => + values[fn]((value) => { + const type = typeof value as TypeName; + + let result = MAP_TO_VALUE_IS_EMPTY_FUNCTION[type](value); + + if (not) { + result = !result; + } + + return result; + }); + +export default isEmpty; diff --git a/striker-ui/types/MapToType.d.ts b/striker-ui/types/MapToType.d.ts new file mode 100644 index 00000000..69bfeea2 --- /dev/null +++ b/striker-ui/types/MapToType.d.ts @@ -0,0 +1,4 @@ +declare type MapToType = { + number: number; + string: string; +};