Last active
October 9, 2024 23:35
-
-
Save toky-nomena/59fc7fe9919f3f85b32ed9c1365f31fc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Nullable<T> = T | undefined | null; | |
function isDefined<T>(item: T): item is NonNullable<T> { | |
return item !== undefined && item !== null; | |
} | |
function compact<T, R>( | |
list: Nullable<T[]>, | |
mapFn: (item: NonNullable<T>) => Nullable<R> | |
): R[] { | |
if (!list) { | |
return []; | |
} | |
return list.reduce((acc: R[], item) => { | |
if (isDefined(item)) { | |
const mappedItem = mapFn(item); | |
if (isDefined(mappedItem)) { | |
acc.push(mappedItem); | |
} | |
} | |
return acc; | |
}, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment