Skip to content

Instantly share code, notes, and snippets.

@beefchimi
Created September 12, 2019 19:25
Show Gist options
  • Save beefchimi/4cddff89d36f2eac6ac46db2cc712d68 to your computer and use it in GitHub Desktop.
Save beefchimi/4cddff89d36f2eac6ac46db2cc712d68 to your computer and use it in GitHub Desktop.
Format React key
export const regExpCommonCharacters = new RegExp(/[^\w]/gim);
const INDEX_DELIMITER = '-';
const MAX_CHARACTER_LENGTH = 100;
export function formatReactKey(key: string, index: number | null = null) {
const hasIndex = index || index === 0;
const transformedKey = [
...key
.toLowerCase()
.replace(regExpCommonCharacters, '')
.substring(
0,
hasIndex
? MAX_CHARACTER_LENGTH -
(INDEX_DELIMITER.length + index!.toString().length)
: MAX_CHARACTER_LENGTH,
),
]
.map((character) =>
Math.random() > 0.5 ? character.toUpperCase() : character,
)
.join('');
return hasIndex
? `${transformedKey}${INDEX_DELIMITER}${index}`
: transformedKey;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment