Skip to content

Instantly share code, notes, and snippets.

@toky-nomena
Last active October 9, 2024 23:35
Show Gist options
  • Save toky-nomena/59fc7fe9919f3f85b32ed9c1365f31fc to your computer and use it in GitHub Desktop.
Save toky-nomena/59fc7fe9919f3f85b32ed9c1365f31fc to your computer and use it in GitHub Desktop.
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