diff --git a/src/async.ts b/src/async.ts new file mode 100644 index 00000000..ff258037 --- /dev/null +++ b/src/async.ts @@ -0,0 +1,26 @@ +/** + * Loads async import with retries. It can be useful for bad internet connection + * + * @example + * const HeaderLazyComponent = React.lazy(() => asyncImportLoader(() => import('../components/Header/Header'))); + * + * @example + * asyncImportLoader(() => import('some-module'), 20).then((someModule) => { + * someModule.init(); + * }); + */ +export const asyncImportLoader = (asyncImport: () => Promise, attempts = 10): Promise => { + return new Promise((resolve, reject) => { + asyncImport() + .then(resolve) + .catch((error) => { + setTimeout(() => { + if (attempts === 0) { + reject(error); + return; + } + asyncImportLoader(asyncImport, attempts - 1).then(resolve, reject); + }, 1000); + }); + }); +}; diff --git a/src/index.ts b/src/index.ts index 475a7a00..9f822bd3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -54,6 +54,10 @@ export { difference, } from './arrays'; +export { + asyncImportLoader, +} from './async'; + export { getCookie, } from './cookie'; @@ -142,6 +146,10 @@ export type { Writeable, } from './types'; +export { + escapeRegExp, +} from './regexp'; + export { localStorage, sessionStorage, diff --git a/src/regexp.ts b/src/regexp.ts new file mode 100644 index 00000000..8c2f3fc1 --- /dev/null +++ b/src/regexp.ts @@ -0,0 +1,13 @@ +/** + * Escapes a string so that it can be put into RegExp as a variable + * + * @example + * new RegExp(`foo-${escapeRegExp('(bar)')}`, 'i') + */ +export function escapeRegExp(string: string): string { + if (string) { + return string.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); + } + + return ''; +}