1 | import { Platform } from 'react-native';
|
2 |
|
3 | import {
|
4 | PlatformArray,
|
5 | Getter,
|
6 | GetSupportedPlatformInfoAsyncParams,
|
7 | GetSupportedPlatformInfoSyncParams,
|
8 | GetSupportedPlatformInfoFunctionsParams,
|
9 | } from './privateTypes';
|
10 |
|
11 | type MemoType = { [key: string]: any };
|
12 |
|
13 | let memo: MemoType = {};
|
14 |
|
15 | export function clearMemo() {
|
16 | memo = {};
|
17 | }
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | function getSupportedFunction<T>(
|
26 | supportedPlatforms: PlatformArray,
|
27 | getter: Getter<T>,
|
28 | defaultGetter: Getter<T>
|
29 | ): Getter<T> {
|
30 | let supportedMap: any = {};
|
31 | supportedPlatforms
|
32 | .filter((key) => Platform.OS == key)
|
33 | .forEach((key) => (supportedMap[key] = getter));
|
34 | return Platform.select({
|
35 | ...supportedMap,
|
36 | default: defaultGetter,
|
37 | });
|
38 | }
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | export function getSupportedPlatformInfoSync<T>({
|
45 | getter,
|
46 | supportedPlatforms,
|
47 | defaultValue,
|
48 | memoKey,
|
49 | }: GetSupportedPlatformInfoSyncParams<T>): T {
|
50 | if (memoKey && memo[memoKey] != undefined) {
|
51 | return memo[memoKey];
|
52 | } else {
|
53 | const output = getSupportedFunction(supportedPlatforms, getter, () => defaultValue)();
|
54 | if (memoKey) {
|
55 | memo[memoKey] = output;
|
56 | }
|
57 | return output;
|
58 | }
|
59 | }
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 | export async function getSupportedPlatformInfoAsync<T>({
|
66 | getter,
|
67 | supportedPlatforms,
|
68 | defaultValue,
|
69 | memoKey,
|
70 | }: GetSupportedPlatformInfoAsyncParams<T>): Promise<T> {
|
71 | if (memoKey && memo[memoKey] != undefined) {
|
72 | return memo[memoKey];
|
73 | } else {
|
74 | const output = await getSupportedFunction(supportedPlatforms, getter, () =>
|
75 | Promise.resolve(defaultValue)
|
76 | )();
|
77 | if (memoKey) {
|
78 | memo[memoKey] = output;
|
79 | }
|
80 |
|
81 | return output;
|
82 | }
|
83 | }
|
84 |
|
85 |
|
86 |
|
87 |
|
88 |
|
89 | export function getSupportedPlatformInfoFunctions<T>({
|
90 | syncGetter,
|
91 | ...asyncParams
|
92 | }: GetSupportedPlatformInfoFunctionsParams<T>): [Getter<Promise<T>>, Getter<T>] {
|
93 | return [
|
94 | () => getSupportedPlatformInfoAsync(asyncParams),
|
95 | () => getSupportedPlatformInfoSync({ ...asyncParams, getter: syncGetter }),
|
96 | ];
|
97 | }
|