I have a component
export default function PressableText({
children = "",
detectionOptions = Object.keys(PATTERNS).map((type) => ({ type })),
style = commonStyles.text
}) {
...
}
PressableText.propTypes = {
children: PropTypes.string,
detectionOptions: PropTypes.arrayOf(
PropTypes.shape({
type: PropTypes.oneOf(Object.keys(PATTERNS)).isRequired,
onPress: PropTypes.func,
})
),
...
};
As you can see, 'detectionOptions', receives an array of (type, onPress), and the onPress method is optional.
My current PATTERNS object looks like:
export const PATTERNS = {
username: /@[a-zA-Z0-9_.-]{3,30}/,
uri: regexForUri,
phone: regexForPhone,
};
So... basically, what I want to do is to provide a default onPress action for each key.
I have thought to implement a factory, but I am not really good at Design Patterns. Is this considered a factory?
//
// CODE INSIDE MY COMPONENT, AS IT ACCESS COMPONENT RELATED STUFF
//
const handleOnPressUri = () => { ... };
const handleOnPressPhone = () => { ... };
const handleOnPressUsername = () => { ... };
const defaultPressableActions = useMemo( // IS THIS A FACTORY?
() => ({
uri: handleOnPressUri,
phone: handleOnPressPhone,
username: handleOnPressUsername,
}),
[]
);
const getPatterns = () =>
detectionOptions.map(({ type, onPress }) => {
const pattern = PATTERNS[type];
if (pattern) {
return {
pattern,
onPress: onPress ?? defaultPressableActions[type],
};
}
throw new Error(`Invalid pattern type.`);
}
);
I am asking this, because as far as I know, a factory is a generalized that which returns customized stuff, in a centralized way. But... what about a map that, for each key, returns an action?
Is there any other better solution that comes to your mind in order to refactor this code?