Skip to content

Commit

Permalink
fix(t-utils): let negotiators infer the return type from usage
Browse files Browse the repository at this point in the history
  • Loading branch information
macarie committed Mar 1, 2024
1 parent 387742a commit fae07f6
Showing 1 changed file with 19 additions and 14 deletions.
33 changes: 19 additions & 14 deletions packages/t-utils/source/negotiator.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,37 @@
import { filterMatches } from "@fluent/langneg";

export type LocaleNegotiator<Locale> = (
const typedFilterMatches = filterMatches as <
Requested extends string,
Available extends string,
>(
requested: readonly Requested[],
available: readonly Available[],
strategy: "filtering" | "lookup" | "matching",
) => Available[];

export type LocaleNegotiator<TypeParamLocale extends string = string> = <
Locale extends TypeParamLocale,
>(
availableLocales: readonly Locale[],
) => Locale | undefined;

export type LocaleNegotiators<Locale> =
export type LocaleNegotiators<Locale extends string> =
| readonly [...(LocaleNegotiator<Locale> | false)[], Locale]
| readonly [];

type Algorithm = (
type Algorithm = <Available extends string = string>(
requestedLocales: readonly string[],
availableLocales: readonly string[],
) => string[];
availableLocales: readonly Available[],
) => Available[];

export const lookup: Algorithm = (requestedLocales, availableLocales) =>
filterMatches(
// @info `filterMatches` expects mutable arrays
Array.from(requestedLocales),
Array.from(availableLocales),
"lookup",
);
typedFilterMatches(requestedLocales, availableLocales, "lookup");

export const negotiator: (
requestedLocales: readonly string[],
algorithm: Algorithm,
) => LocaleNegotiator<string> =
(requestedLocales, algorithm) => (availableLocales) =>
algorithm(requestedLocales, availableLocales)[0];
) => LocaleNegotiator = (requestedLocales, algorithm) => (availableLocales) =>
algorithm(requestedLocales, availableLocales)[0];

export const browser = () =>
negotiator(globalThis.navigator?.languages ?? [], lookup);

0 comments on commit fae07f6

Please sign in to comment.