UNPKG

2.55 kBPlain TextView Raw
1import { Platform } from 'react-native';
2
3import {
4 PlatformArray,
5 Getter,
6 GetSupportedPlatformInfoAsyncParams,
7 GetSupportedPlatformInfoSyncParams,
8 GetSupportedPlatformInfoFunctionsParams,
9} from './privateTypes';
10
11type MemoType = { [key: string]: any };
12// centralized memo object
13let memo: MemoType = {};
14
15export function clearMemo() {
16 memo = {};
17}
18
19/**
20 * function returns the proper getter based current platform X supported platforms
21 * @param supportedPlatforms array of supported platforms (OS)
22 * @param getter desired function used to get info
23 * @param defaultGetter getter that returns a default value if desired getter is not supported by current platform
24 */
25function 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 * function used to get desired info synchronously — with optional memoization
42 * @param param0
43 */
44export 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 * function used to get desired info asynchronously — with optional memoization
63 * @param param0
64 */
65export 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 * function that returns array of getter functions [async, sync]
87 * @param param0
88 */
89export 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}