Skip to content

Commit

Permalink
feat(util): renderState
Browse files Browse the repository at this point in the history
  • Loading branch information
alimd committed Jun 14, 2023
1 parent 18c9458 commit 19a6030
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
3 changes: 3 additions & 0 deletions core/util/src/_logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import {createLogger} from '@alwatr/logger';

export const logger = createLogger('alwatr/util');
1 change: 1 addition & 0 deletions core/util/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export * from './client-id.js';
export * from './polyfill.js';
export * from './flat-str.js';
export * from './string.js';
export * from './render-state.js';
46 changes: 46 additions & 0 deletions core/util/src/render-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import {logger} from './_logger.js';

export const renderState = <R, T extends string>(
state: T,
renderRecord: Record<T | '_default', undefined | T | (() => R)>,
thisArg: unknown = null,
): R | void => {
logger.logMethodArgs?.('renderState', {state, renderRecord});

let render = renderRecord[state];

if (typeof render === 'string') {
render = renderRecord[render as T];
}

if (render === undefined) {
if (renderRecord._default === undefined) {
logger.error('renderState', 'invalid_render_state');
return;
}
// else
if (typeof renderRecord._default === 'string') {
if (renderRecord[renderRecord._default] === undefined) {
logger.error('renderState', 'invalid_default_render');
return;
}
// else
return renderState(renderRecord._default, renderRecord, thisArg);
}
// else
render = renderRecord._default;
}

if (typeof render !== 'function') {
logger.error('renderState', 'invalid_render_state');
return;
}

try {
return render.call(thisArg);
}
catch (err) {
logger.error('renderState', 'render_error', err);
return;
}
};

0 comments on commit 19a6030

Please sign in to comment.