-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(t-utils): let negotiators infer the return type from usage
- Loading branch information
Showing
1 changed file
with
19 additions
and
14 deletions.
There are no files selected for viewing
This file contains 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
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); |