90 lines
2.4 KiB
TypeScript
90 lines
2.4 KiB
TypeScript
import Taro from '@tarojs/taro';
|
|
|
|
export const isDev = () => process.env.NODE_ENV === 'development';
|
|
// export const isDev = () => true;
|
|
|
|
export const isIPhone = (() => {
|
|
const info = Taro.getDeviceInfo();
|
|
return info.platform === 'ios';
|
|
})();
|
|
|
|
export const isDesktop = (() => {
|
|
const info = Taro.getDeviceInfo();
|
|
return info.platform === 'windows' || info.platform === 'mac';
|
|
})();
|
|
|
|
|
|
export const logWithPrefix = isDev()
|
|
? (prefix: string) =>
|
|
(...args: BL.Anything[]) =>
|
|
console.log(`[${prefix}]`, ...args)
|
|
: (_prefix: string) =>
|
|
(..._args: BL.Anything[]) => {};
|
|
|
|
export const safeJsonParse = <T = BL.Anything>(str: string, defaultValue: BL.Anything = {}): T => {
|
|
try {
|
|
return JSON.parse(str);
|
|
} catch (e) {
|
|
return defaultValue;
|
|
}
|
|
};
|
|
|
|
export const string2Number = (str: string, defaultValue: number = 0) => {
|
|
if (!str) {
|
|
return defaultValue;
|
|
}
|
|
const num = Number(str);
|
|
return Number.isNaN(num) ? defaultValue : num;
|
|
};
|
|
|
|
export const isUndefined = (v: BL.Anything) => typeof v === 'undefined';
|
|
|
|
export const sleep = (timeout: number = 3) => new Promise(resolve => setTimeout(resolve, timeout * 1000));
|
|
|
|
export const last = <T = BL.Anything>(list: T[]) => list[list.length - 1];
|
|
|
|
export function oncePromise<T extends BL.Anything[], R extends BL.Anything>(
|
|
func: AsyncFunction<T, R>
|
|
): AsyncFunction<T, R> {
|
|
let task: Promise<R> | null = null;
|
|
return async (...args: T): Promise<R> => {
|
|
if (task) {
|
|
console.log('[once promise]: has task pending');
|
|
return task;
|
|
}
|
|
try {
|
|
task = func(...args);
|
|
const result = await task;
|
|
return result;
|
|
} catch (e) {
|
|
throw e;
|
|
} finally {
|
|
task = null;
|
|
}
|
|
};
|
|
}
|
|
|
|
export const copy = (content: string): Promise<TaroGeneral.CallbackResult> => {
|
|
return new Promise((resolve, reject) => {
|
|
Taro.setClipboardData({
|
|
data: content,
|
|
success: resolve,
|
|
fail: reject,
|
|
});
|
|
});
|
|
};
|
|
|
|
export const openCustomerServiceChat = (url: string = 'https://work.weixin.qq.com/kfid/kfc291d0b01ecda3088') => {
|
|
Taro.openCustomerServiceChat({
|
|
extInfo: { url },
|
|
corpId: 'ww4f2f2888bf9a4f95',
|
|
});
|
|
};
|
|
|
|
export const isValidIdCard = (idCard: string) =>
|
|
/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(idCard);
|
|
|
|
export const isValidPhone = (phone: string) => /^1[3-9]\d{9}$/.test(phone);
|
|
|
|
export const getScrollItemId = (id?: string) => (id ? `sid-${id}` : id);
|