Skip to content

Commit

Permalink
Merge pull request #28 from VKCOM/add-funcs
Browse files Browse the repository at this point in the history
Add functions
  • Loading branch information
fedorov-xyz authored Mar 26, 2021
2 parents 4d26463 + 08cf202 commit 6a4ed67
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/async.ts
Original file line number Diff line number Diff line change
@@ -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 = <T>(asyncImport: () => Promise<T>, attempts = 10): Promise<T> => {
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);
});
});
};
8 changes: 8 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ export {
difference,
} from './arrays';

export {
asyncImportLoader,
} from './async';

export {
getCookie,
} from './cookie';
Expand Down Expand Up @@ -142,6 +146,10 @@ export type {
Writeable,
} from './types';

export {
escapeRegExp,
} from './regexp';

export {
localStorage,
sessionStorage,
Expand Down
13 changes: 13 additions & 0 deletions src/regexp.ts
Original file line number Diff line number Diff line change
@@ -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 '';
}

0 comments on commit 6a4ed67

Please sign in to comment.