Skip to content

Instantly share code, notes, and snippets.

@elierotenberg
Last active March 5, 2024 12:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elierotenberg/261f8a008c6062c257878eb1631f5276 to your computer and use it in GitHub Desktop.
Save elierotenberg/261f8a008c6062c257878eb1631f5276 to your computer and use it in GitHub Desktop.
Maybe with fallback
const { app_by_id } = await gql.getMiddlewareData({ app_id: MOSAIC_APP_ID });
const appLocaleList = maybe(app_by_id, `App not found`)
.pipe((app) => app.locale, `App locale not found`)
.get()
.map((appLocale) =>
appLocale?.locale_code
? {
code: appLocale.locale_code.code,
isDefault: appLocale.is_default,
slug: appLocale.slug,
}
: null,
)
.filter(isNonNullable);
export const isNonNullable = <T>(value: T): value is NonNullable<T> =>
typeof value !== `undefined` && value != null;
export class Maybe<T> {
private readonly value: T;
private readonly notFoundMessage: string;
public constructor(value: T, notFoundMessage: string) {
this.value = value;
this.notFoundMessage = notFoundMessage;
}
public readonly pipe = <U>(
fn: (value: NonNullable<T>) => U,
notFoundMessage?: string,
): Maybe<U> | Maybe<U | null> => {
if (isNonNullable(this.value)) {
return new Maybe<U>(
fn(this.value),
notFoundMessage ?? this.notFoundMessage,
);
}
return new Maybe<U | null>(null, this.notFoundMessage);
};
public readonly fallback = <F extends NonNullable<T>>(
fallbackValue: F,
): NonNullable<T> | F => {
if (isNonNullable(this.value)) {
return this.value;
}
return fallbackValue;
};
public readonly get = (): NonNullable<T> => {
if (isNonNullable(this.value)) {
return this.value;
}
throw new Error(this.notFoundMessage);
};
}
export const maybe = <T>(
value: T | null | undefined,
notFoundMessage: string,
) => new Maybe(value, notFoundMessage);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment